Search code examples
powershellpowershell-3.0

Global scope variable is null within Scriptblock


Running the following code produces an error because the variable used for path is resolved as null event though it defined in the script:

$ServerName = "test01"
$RemotePath = "C:\Test\"
$TestScriptBlock = { copy-item -Path $RemotePath  -Destination C:\backup\ -Force -Recurse } 
$CurrentSession = New-PSSession -ComputerName $ServerName

Invoke-Command -Session $CurrentSession -ScriptBlock $TestScriptBlock 

How do I call the $RemotePath defined in the parent script from within the ScriptBlock? I need to use $RemotePath in other parts of the parent script. Note, this value doesn't change, so it can be a constant.

UPDATE -- WORKING SOLUTION

You have to pass in variable as parameter to the scriptblock:

$ServerName = "test01"
$RemotePath = "C:\Test\"
$TestScriptBlock = { param($RemotePath) copy-item -Path $RemotePath  -Destination C:\backup\ -Force -Recurse } 
$CurrentSession = New-PSSession -ComputerName $ServerName

Invoke-Command -Session $CurrentSession -ScriptBlock $TestScriptBlock -ArgumentList $RemotePath 

Solution

  • You've got two scripts there, not one. The $TestScriptBlock is a separate script nested inside the main one, you send it to the remote computer, and that remote computer doesn't have $RemotePath configured. Try:

    $ServerName = "test01"
    
    $TestScriptBlock = {
        $RemotePath = "C:\Test\"
        copy-item -Path $RemotePath  -Destination C:\backup\ -Force -Recurse 
    }
    
    $CurrentSession = New-PSSession -ComputerName $ServerName
    
    Invoke-Command -Session $CurrentSession -ScriptBlock $TestScriptBlock
    

    (I would probably call it $LocalPath then, though)