【发布时间】:2020-01-27 17:29:04
【问题描述】:
这似乎很奇怪,但我无法为 Invoke-Command 内的变量赋值。这是下面的代码,但是当打印出 $targetComputerPath 时,它只是空的。怎么了?
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
}
【问题讨论】:
-
@AdminOfThings:一般来说,是的,但是这里涉及到 remoting,所以你根本无法从 远程执行 脚本块修改调用者的变量.
-
旁注:要找出设备的 Windows 版本,查看 AD 记录就足够了(
Get-ADComputer $computername -Properties operatingSystemVersion | select name,operatingSystemVersion- 即使机器离线也可以使用)。如果这就是您需要知道的全部内容,您可以完全删除 WinRM/Invoke-Command并大大简化您的脚本。
标签: powershell