2

I have a script (pasted below) that's supposed to do the following:

  1. Loops and grabs all files that match a defined pattern
  2. Copies those files into another location
  3. Move the original source file into another location (if copy was successful)

It's doing step #1 and #2 but step #3, Move-Item is not moving any files and I don't know why and I get no indication of an error

Can someone help? Thanks

$source = "C:\Users\Tom\"
$source_move = "C:\Users\Tom\OldLogBackup1\"
$destination ="C:\Users\Tom\Mirror\"

if(-not(Test-Path $destination)){mkdir $destination | out-null}

#Step 1
ForEach ($sourcefile In $(Get-ChildItem $source | Where-Object { $_.Name -match "Daily_Reviews\[\d\d\d\d-\d\d\d\d\].journal" }))
{
    #escape filename because there are brackets in the name!
$src = [Management.Automation.WildcardPattern]::Escape($sourcefile)

    #Step 2
    Copy-Item  $src $destination

### Check for a successful file copy
if($?)
{


    if(-not(Test-Path $source_move)){
        echo "Path does not exist!"
    } else { 
        echo "Path exists!"

        ### Step 3
                    ### Move original source file someplace else
        Move-Item $source_move$sourcefile $source_move
        if($?)
        {
            echo "Source file successfully moved"

        } else {

            echo "Source file was not successfully moved"

    }
  }
}
Slinky
  • 1,027
  • 3
  • 15
  • 26

2 Answers2

3

First, it looks like you're moving the files into the same directory they started from...from the $source_move to the $source_move. I think you want it to look like this:

Move-Item $source + $sourcefile $source_move

Also, try putting a + between $source_move and $sourcefile.

Snowburnt
  • 775
  • 2
  • 5
  • 18
0

This is exactly your problem. You can't chain variables together like that. PoSh gets confused.

Try this:

PS C:\> $a = "Powershell"
PS C:\> $b = " Rocks!"
PS C:\> $a
Powershell
PS C:\> $b
 Rocks!
PS C:\> $a$b
At line:1 char:3
+ $a$b
+   ~~
Unexpected token '$b' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

PS C:\> $a+$b
Powershell Rocks!
PS C:\> "$a$b"
Powershell Rocks!

AND you were trying to move to the same folder (source = destination). This is always a no no.

John Homer
  • 1,313
  • 1
  • 10
  • 10