Search code examples
powershellpowershell-remoting

PS invoke-command and writeallbyes


So.. as in the topic - I am using Invoke-Command to copy a file to a remote location.

without further do let's go to the code:

$Contents = [System.IO.File]::ReadAllBytes("$workingDir\$FileToCopy")
[string]$FileTo = "C:\$installer"
$result = Invoke-Command -Computername $servername -Credential $Credentials -Scriptblock {
    param(
                   [byte[]]
                   $Contents
               )
    [System.IO.File]::WriteAllBytes($FileTo, $Contents)
    return $? 
} -ArgumentList @( ,$Contents )
$result

The issue is that if I replace $FileTo to a manual entry, like this:

[System.IO.File]::WriteAllBytes("C:\MyFileToCopy.txt", $Contents)

all is good, otherwise when I put the path to the file into a string variable - I receive the following error:

Exception calling "WriteAllBytes" with "2" argument(s): "Empty path name is not legal."
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentException

Why?


Solution

  • You're not sending $FileTo as an argument to the remote system.

    I would use using to access the content of the variable like:

    [System.IO.File]::WriteAllBytes($using:FileTo, $Contents)