脚本块中的全局作用域变量为空。

8
运行以下代码会出现错误,因为虽然在脚本中定义了路径变量,但它被解析为null。
$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 

如何从ScriptBlock内部调用父脚本中定义的$RemotePath?我需要在父脚本的其他部分使用$RemotePath。请注意,这个值不会改变,所以它可以是一个常量。 更新--可行解决方案 你必须将变量作为参数传递到脚本块中:
$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 

你可以尝试使用 $global:RemotePath = "C:\Test" 作为全局变量,该变量可以在整个脚本文件中任何地方访问。 - Nipun
尝试过了,不起作用。 - user2896050
$using:RemotePath 有效吗? - Dan Stevens
3个回答

3
你有两个脚本,而非一个。$TestScriptBlock是在主脚本中嵌套的独立脚本,你将其发送到远程计算机,但该计算机没有配置$RemotePath。尝试以下方法:
$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

(我可能会称其为$LocalPath,尽管如此)

有没有办法在这个父脚本中定义一个全局变量,以便我可以在脚本块和父脚本中使用它?否则,我需要在脚本中维护重复的变量,因为我需要在脚本块之外的其他位置使用它。请注意,此值不会更改,因此可以是常量。 - user2896050
是的,也许可以,虽然我没有尝试过 - http://powershell.com/cs/blogs/tips/archive/2012/10/26/executing-code-locally-and-remotely-using-local-variables.aspx 看起来会有所帮助。 - TessellatingHeckler
我通过你在评论中提供的链接解决了问题。我会在上面添加一个更新,以便其他人可以看到解决方案。谢谢。 - user2896050

2

尝试使用以下语法:

$globalvariable1 = "testoutput01"
$globalvariable2 = "testoutput02"

$Scriptblock = {
    Write-Host $using:globalvariable1
    Write-Host $using:globalvariable2
}

$serverName = Domain\HostNameofServer

Invoke-Command -ComputerName $serverName -ScriptBlock $ScriptBlock -ArgumentList $globalvariable1, $globalvariable2

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接