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