【问题标题】:Powershell foreach - variable not workPowershell foreach - 变量不起作用
【发布时间】:2015-09-18 15:23:36
【问题描述】:

我的 miniScript 不工作...为什么?:

Get-VM | select name | ? { $_.Name -like "*411D*" } -OutVariable VmWareName
$VmWareName |foreach {
     Restore-VMSnapshot -Name * -VMName $_ -Confirm:$false
}

对不起,不会英文

【问题讨论】:

  • 它不起作用怎么办?你有错误吗? $VmWareName 变量是否未设置?循环不工作吗?
  • 循环工作。如果我只制作“$_”,那么输出是完美的。这里的错误: "0" konnte nicht mit "" verglichen werden。费勒:“Der Wert "System.Object[]" vom Typ "System.Object[]" kann nicht in den Typ "System.Int32" konvertiert werden。在 Zeile:5 Zeichen:12 + for ($i=0; $i -lt $VmWareName.Length; $i++) + ~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : ComparisonFailure
  • Restore-VMSnapshot documentation 使您看起来无法将*-Name 一起使用。修复它是否使它工作?该文档还提供了有关如何恢复最新快照的示例。
  • Restore-VMSnapshot -Name * -VMName 411D-SRV -Confirm:$false - 这行得通。问题是 foreach 中的 $_...
  • 有问题您使用ForEach-Object cmdlet,但错误,您在cmets 中发布,显示for 循环。

标签: powershell foreach


【解决方案1】:

问题是你输出的对象只有一个属性:名称

你想要的是一个字符串,带有 Name 属性的值。您有 2 个选项。在循环中引用对象的 Name 属性,如下所示:

     Restore-VMSnapshot -Name * -VMName $_.Name -Confirm:$false

或者当你像这样将它保存到你的变量时展开 Name 属性:

Get-VM | select -Expandproperty name | ? { $_ -like "*411D*" } -OutVariable VmWareName

【讨论】:

  • 谢谢,那个脚本更好(输出)。但这行不通。 Powershell说无法检查参数“VmName”。参数为 null 或为空
  • 有效:Get-VM |选择-展开属性名称 | ? { $_ -like "411D" } -OutVariable VmWareName | %{ 恢复-VMSnapshot -Name * -VMName $_ -Confirm:$false}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 2019-06-11
相关资源
最近更新 更多