使用 $using 找不到 Sitecore PowerShell Remoting 变量

Sitecore PowerShell Remoting variable not found $using

我最近开始使用 PowerShell,并且正在编写一个小脚本,用于使用 Sitecore PowerShell 扩展和远程处理来安装 Sitecore 包。

我创建了以下脚本:

$session = New-ScriptSession -Username admin -Password b -ConnectionUri  http://sitecore

$identity = "admin"
$date = [datetime]::Now

$jobId = Invoke-RemoteScript -Session $session -ScriptBlock {
    [Sitecore.Security.Accounts.User]$user = Get-User -Identity $using:identity
    $user.Name
} -AsJob
Wait-RemoteScriptSession -Session $session -Id $jobId -Delay 5 -Verbose

我的脚本在 PowerShell ISE 中 运行 正常,但在 PowerShell 命令提示符中我收到以下错误:

Get-Variable : Cannot find a variable with the name 'date'. 
At C:\Users\Administrator\Documents\WindowsPowerShell\Modules\SPE\SPE.psm1:21 char:26
+ ...    $value = Get-Variable -Name $Var.SubExpression.VariablePath.UserPa ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (date:String) [Get-Variable], ItemNotFoundException
+ FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

Get-Variable : Cannot find a variable with the name 'identity'.
At C:\Users\Administrator\Documents\WindowsPowerShell\Modules\SPE\SPE.psm1:21 char:26
+ ...    $value = Get-Variable -Name $Var.SubExpression.VariablePath.UserPa ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (identity:String) [Get-Variable], ItemNotFoundException
+ FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

显然我无法访问命令提示符中的变量,但在 ISE 中找不到 $using: 变量。

我对 PowerShell 的经验很少,我不确定为什么会这样。

您可以尝试使用 -Arguments 参数传递参数:

$session = New-ScriptSession -Username admin -Password b -ConnectionUri  http://sitecore

$identity = "admin"
$date = [datetime]::Now

$jobId = Invoke-RemoteScript -Session $session -ScriptBlock {
    [Sitecore.Security.Accounts.User]$user = Get-User -Identity ($params.identity)
    $user.Name
} -AsJob -Arguments @{identity=$identity}
Wait-RemoteScriptSession -Session $session -Id $jobId -Delay 5 -Verbose

Thomas,我怀疑您使用的是旧版本的 SPE Remoting 模块。你能升级到 4.3 吗?

出于某种原因,在使用 Windows PowerShell 5.1 和 SPE 4.3 进行测试时,该模块在 Windows PowerShell ISE 中的一个稍微不同的场景中对我不起作用。

我报告了一个 issue 来解决我的问题,希望能解决你的问题。

您提供的示例应该可以正常工作,因为它看起来像是来自文档。

更新

问题 #772

我终于能够在控制台中重现您缺少变量的问题;我已经更新了 SPE Remoting 模块来解决这种情况。

我还解决了 Start-ScriptSession 在将 Invoke-RemoteScript 作为作业调用时未正确使用 $using 变量的问题。

期待在 4.3.1+ 中看到修复。