Problems passing variable to move-item in invoke-command

by kblackwell at 2012-10-22 11:39:48

I have a directory on a remote server that I do get returned a true if I test-path.

Test-Path "D:\DFSRoot1\Home\HXXXXXX$SamAcct"

So I would expect this to work
Invoke-Command -ComputerName idn-comp -ScriptBlock {Move-Item -Path D:\DFSRoot1\Profile\Hoffman$($SamAcct) -Destination D:\DFSRoot1\Profile}

But I always get this result.

Source and destination path must be different.
+ CategoryInfo : WriteError: (D:\DFSRoot1\Home\HXXXXXX:DirectoryInfo) [Move-Item], IOException
+ FullyQualifiedErrorId : MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

My thought are that the variable is being expanded on the remote machine that does not know the value of $SamAcct. So, how do I expand before it’s run on remote server?
I’m running this through a loop, so the directory name is always being held in a variable.

Either way I always get that error. Any thoughts?
by poshoholic at 2012-10-22 12:06:28
Are you using PowerShell 3? If so, you should be able to simply prefix your variable with using:, like this:
Invoke-Command -ComputerName idn-comp -ScriptBlock {Move-Item -Path D:\DFSRoot1\Profile\Hoffman$($using:SamAcct) -Destination D]
If you’re not using PowerShell 3, then you can pass in arguments using the -ArgumentList parameter of Invoke-Command, and then reference those arguments inside the script block, either as named arguments if you use a param statement or as unnamed arguments by using $args[0], $args[1], and so on.
by DexterPOSH at 2012-10-22 14:50:44
Cool PowerShell v3 trick…Kirk