【问题标题】:Variable not passing through? [duplicate]变量不通过? [复制]
【发布时间】:2021-01-15 07:20:51
【问题描述】:

大家下午好!

我可以得到一些帮助,或者至少用下面的脚本指出正确的方向吗?

我正在使用戴尔 BIOS,并且已经成功地获得了我们正在寻找的工作,让远程 PC 将某个类别设置为已禁用或已启用。现在的问题是,在尝试创建脚本时,选择的变量确实通过并且只是循环到选择的第一列。见下文:


$PSSession = New-PSSession -ComputerName $CName
Write-Host "Please wait will module is loaded"


Invoke-Command -Session $PSSession {Import-Module DellBIOSProvider} 
Start-Sleep 1

$FConfigs = Invoke-Command -Session $PSSession { Get-ChildItem -path "DellSMBios:\" | Select-Object -ExpandProperty Category}

for ($i=0; $i -lt $FConfigs.Count; $i++) {
  Write-Host "$($i): $($FConfigs[$i])"
  }

$selection1 = Read-Host "Enter the number you'd like to change"
$selection =  $Fconfigs[$selection1]

Start-Sleep 2
$SConfigs = Invoke-Command -Session $PSSession { Get-ChildItem -path "DellSMBios:\$selection" | Select-Object -ExpandProperty Category}
for ($i=0; $i -lt $SConfigs.Count; $i++) {
  Write-Host "$($i): $($SConfigs[$i])"
  }

$selection1 = Read-Host "Enter the number you'd like to change"
$selection =  $Sconfigs[$selection1]
"$selection"        

所以在$FConfigs 的选择中,$selection 获得了适当的选择,但是它不会传递给$SConfigs。这是因为,它在$Sconfigs 中显示了完全相同的$FConfigs 选择。 请注意:我已经验证我选择的任何选项都包含属性,所以gci "dellsmbios:\$selection" 应该可以工作。

希望这是有道理的,有人可以告诉我我做错了什么。

【问题讨论】:

  • 简而言之:因为脚本块远程执行,它对调用者的变量一无所知。引用调用者变量值的最简单方法是使用 $using: 范围 - 请参阅 this answer

标签: powershell powershell-5.0


【解决方案1】:
$SConfigs = Invoke-Command -Session $PSSession { Get-ChildItem -path "DellSMBios:\$selection" | Select-Object -ExpandProperty Category}

在这一行中,将$selection 更改为$using:selection

在远程会话中使用局部变量时需要这样做。您可以在“使用局部变量”下阅读更多相关信息:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-7.1

【讨论】:

  • 嘿,对不起,我忘了把你的答案标记为答案。它确实奏效了!
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2020-11-08
  • 2018-04-06
  • 1970-01-01
  • 2021-04-10
相关资源
最近更新 更多