Home > front end >  PowerShell Error Copying a folder to remote server
PowerShell Error Copying a folder to remote server

Time:12-31

am trying for a long time to copy the following folder to remote server but unfortunately giving always error. I try alot of ways :((((

I really need a help

The code:


$ServerLists = Get-Content -Path "c:\scripts\serverslist.txt"
$NewRFCName = Read-Host -Prompt 'Enter New RFC Name'
 foreach ($server in $ServerLists)
        {
           $from =  "C:\Releases\"   $NewRFCName
           $exchange = New-PSSession -ComputerName $server -Credential $Credential
          #    #######Copy the new pakage to Website folder : #######
          Write-Host "server :$server \\ Copying the new pakgae to Website folder "
          Invoke-Command -Session $exchange -ScriptBlock {Copy-Item $from  C:\site -Recurse}
        }

The Error:

Cannot bind argument to parameter 'Path' because it is null.

CodePudding user response:

The scriptblock passed to Invoke-Command will be executed on the remote machine, where the $from variable doesn't exist.

You can force PowerShell to copy it's value to the remote session by specifying the using: prefix:

$ServerLists = Get-Content -Path "c:\scripts\serverslist.txt"
$NewRFCName = Read-Host -Prompt 'Enter New RFC Name'

foreach ($server in $ServerLists) {
    $from = "C:\Releases\"   $NewRFCName
    $exchange = New-PSSession -ComputerName $server -Credential $Credential
    #    #######Copy the new pakage to Website folder : #######
    Write-Host "server :$server \\ Copying the new pakgae to Website folder "
    Invoke-Command -Session $exchange -ScriptBlock { Copy-Item $using:from  C:\site -Recurse }
}

Or by explicitly passing it as an argument to the remote session:

Invoke-Command -Session $exchange -ScriptBlock { param([string]$Path) Copy-Item $Path C:\site -Recurse } -ArgumentList $from
  • Related