Powershell 无法为Invoke命令内的变量赋值
这似乎很奇怪,但我不能在Invoke命令中为变量赋值。下面是代码,但当打印出$targetComputerPath时,它只是空的。怎么了Powershell 无法为Invoke命令内的变量赋值,powershell,Powershell,这似乎很奇怪,但我不能在Invoke命令中为变量赋值。下面是代码,但当打印出$targetComputerPath时,它只是空的。怎么了 foreach ($item in $computersPath){ $computername = $item.Name $username = $item.UserID Write-Host computer $computername and user $username if (Test-Connection -C
foreach ($item in $computersPath){
$computername = $item.Name
$username = $item.UserID
Write-Host computer $computername and user $username
if (Test-Connection -ComputerName $computername -Count 1 -ErrorAction SilentlyContinue)
{
if ($((Get-Service WinRM -ComputerName $computername).Status) -eq "stopped")
{
(Get-Service WinRM -ComputerName $computername).Start()
}
Invoke-Command -ComputerName $computername -ScriptBlock {
if ($((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId) -eq "1903" )
{
$targetComputerPath = "\\"+$computername+"\c$\Users\"+$username+"\Desktop\"
write-host "1903"
}
else
{
$targetComputerPath = "\\"+$computername+"\c$\Users\"+$username+"\Desktop\"
write-host "something else"
}
}
}
write-host $targetComputerPath
}
WinRM的要点是获取一个脚本块,并在另一台机器上执行它 您在主机脚本中定义的变量在远程计算机上都不可用 当您将任务(也称为脚本块)与Invoke命令分离时,这一点变得更加明显,如下所示: $task={ $version=获取项目属性-路径HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion 如果$version.ReleaseId-eq 1903{ 注意,“$username”在这里不可用,它从未定义过! 返回\\$env:COMPUTERNAME\c$\Users\$username\Desktop }否则{ 返回\\$env:COMPUTERNAME\c$\Users\$username\Desktop } } $computersPath中的每个$item{ $computername=$item.Name $username=$item.UserID 写入主机$computername和用户$username 如果测试连接-ComputerName$ComputerName-计数1-ErrorAction SilentlyContinue{ $winrm=获取服务winrm-ComputerName$ComputerName 如果$winrm.Status-eq已停止{$winrm.Start} $targetComputerPath=调用命令-ComputerName$ComputerName-ScriptBlock$task 写入计算机返回的主机:$targetComputerPath } } 如您所见,您可以从脚本块返回值,这些值将作为Invoke命令的返回值提供
如果要将参数传递给脚本块,此线程将讨论:做得好;链接的问题更具体地说是关于传递命名参数以调用命令;我建议在这两个链接之间也链接到,OP应该能够找到它。@AdminOfThings:一般来说,是的,但这里涉及远程处理,因此您根本无法从远程执行的脚本块修改调用方的变量。旁注:要找到设备的Windows版本,查看AD记录就足够了获取ADComputer$computername-Properties operatingSystemVersion |选择名称,operatingSystemVersion-即使在机器脱机时也能工作。如果您只需要知道这些,就可以完全删除WinRM/Invoke命令,并大大简化脚本。