Search code examples
powershellpowershell-3.0powershell-remoting

Powershell Copy-Item remote machine copying to wrong location


I am on server A (dev box) creating a remote Powershell session to server B (IIS server). The script copies from server C (build machine) to server B.

I got passed (I think) the multi-hop credential issue EXCEPT the copy is copying to the wrong location on server B.

It is supposed to copy to d:\wwwroot\HelloWorld but instead is copying to c:\users\me\Documents\HelloWorld.

All servers are Win2012r2 and on a domain using powershell v3.

run on server B:

winrm set winrm/config/service/auth '@{CredSSP="true"}'

run on server A:

winrm set winrm/config/client/auth '@{CredSSP="true"}'

And here is my script:

$password = ConvertTo-SecureString "mypassword" -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ("mydomain\me", $password)
$sesh = new-pssession -computername "ServerB" -credential $cred -Authentication CredSSP

$sitePath = "D:\wwwroot\HelloWorld"
Invoke-Command -Session $sesh -ScriptBlock { 
    Copy-Item -path "\\ServerC\Builds\HelloWorld\HelloWorld.1\_PublishedWebsites\HelloWorld" -Destination $sitePath -Recurse -Force
} 

Why isn't it listening to my destination?


Solution

  • Read the remote variable documentation. Your $Sitepath is defined locally and is not defined in the remote script block.

    So either use the syntax that brings in a local variable:

    $sitePath = "D:\wwwroot\HelloWorld"
    Invoke-Command -Session $sesh -ScriptBlock { 
        Copy-Item -path "\\ServerC\Builds\HelloWorld\HelloWorld.1\_PublishedWebsites\HelloWorld" 
                  -destination $Using:sitePath -Recurse -Force
    } 
    

    Or define it in the Script Block:

    Invoke-Command -Session $sesh -ScriptBlock { 
        $sitePath = "D:\wwwroot\HelloWorld"
        Copy-Item -path "\\ServerC\Builds\HelloWorld\HelloWorld.1\_PublishedWebsites\HelloWorld" -Destination $sitePath -Recurse -Force
    }