我正在使用Invoke-Command
,并且在-ScriptBlock
我正在使用的范围内Start-Job
。我必须使用$Using:var
withinStart-Job
但会话正在查找本地会话中声明的变量(之前声明Invoke-Command
)。这是我正在做的一个非常简短的示例:
Invoke-Command -ComputerName $computer -ScriptBlock {
$sourcePath = 'C:\Source'
$destPath = 'C:\dest.zip'
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$includeBaseDirectory = $false
Start-Job -Name "compress_archive" -ScriptBlock {
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory("$using:sourcePath","$using:destPathTemp",$using:compressionLevel,$using:includeBaseDirectory)
}
}
Invoke-Command : The value of the using variable '$using:sourcePath' cannot be retrieved because it has not been set in the local session.
At line:1 char:1
+ Invoke-Command -ComputerName vode-fbtest -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Command], RuntimeException
+ FullyQualifiedErrorId : UsingVariableIsUndefined,Microsoft.PowerShell.Commands.InvokeCommandCommand
$using
如果我在调用变量时省略了,Start-Job -ScriptBlock {}
那么我会得到一个Cannot find an overload for "CreateFromDirectory" and the argument count: "4".
错误,因为变量没有在那个范围内定义。
有没有一种方法可以用于远程$using
会话中的变量而不是本地变量,或者我可以指定另一个范围来从远程会话中获取变量?我可以在修复此问题之前在本地声明这些变量,但由于变量包含动态值(所有这些都在 a 中,其数据是在远程计算机上检索的,所以我需要做大量工作)如果我无法完成这项工作,请重组整个脚本)。Invoke-Command
foreach ($obj in $objects)
如果这有什么不同,我在 Windows Server 2012 R2(源主机和-ComputerName
调用命令的主机)上使用 PS v5.1。
查看这个答案,我发现您可以将变量公开给较低级别的脚本块,但我需要从远程会话中实际声明变量。该值需要来自运行远程会话的计算机。您能否在远程会话中声明变量,使其可用于顶级脚本块中的脚本块?