首页 > 解决方案 > 为另一个脚本重写 Powershell 行

问题描述

有这个现有的 PS 片段可以按预期工作:

$creds = New-Object -TypeName System.Management.Automation.PSCredential ("USERID", (new-object System.Security.SecureString));
$FullVM | Where-Object {$_.runtime.powerState -eq "PoweredOn"} | 
    Select-Object -Property Name,@{N="GuestId";E={$_.Guest.GuestId}},
      @{N="Installed Guest OS";E={$_.Guest.GuestFullName}},
      @{N="Configured Guest OS";E={$_.Config.GuestFullName}},
      @{N="ACCESS";E={$CurrentSession=New-SSHSession -ComputerName $_.Name -AcceptKey -keyfile C:\temp\key.txt -Credential $creds ;(Invoke-SSHCommand -SSHSession $CurrentSession -Command "echo YES" -OutVariable result).output}} 

基本上,据我了解,它收集数据并将它们保存到变量“或对象?”。

对于最后一行,它尝试通过 SSH 连接到远程机器(在 $_.Name 中定义)并在成功时回显“YES”并将其保存到“对象”“ACCESS”中:

@{N="ACCESS";E={$CurrentSession=New-SSHSession -ComputerName $_.Name -AcceptKey Credential $creds ;(Invoke-SSHCommand -SSHSession $CurrentSession -Command "echo YES" -OutVariable result).output}}

我现在遇到的问题是试图弄清楚如何将同一行注入/附加/重写:

  foreach ($vmguest in $FullVM) {
       $vmguest.Config.Hardware.Device | Where-Object {$vmguest.Guest.GuestFullName -cnotlike "*Microsoft*" -and  $_.GetType().Name -match $unwantedHardware} | Foreach-Object {
          New-Object -TypeName PSObject -Property @{
             Name = $vmguest.name
             Label = $_.DeviceInfo.Label
             OS = $vmguest.Guest.GuestFullName
          }
       }
    }

我该如何重写它,以便它仍然提供与前一个片段相同的功能?我这样写吗?

foreach ($vmguest in $FullVM) {
       $vmguest.Config.Hardware.Device | Where-Object {$vmguest.Guest.GuestFullName -cnotlike "*Microsoft*" -and  $_.GetType().Name -match $unwantedHardware} | Foreach-Object {
          New-Object -TypeName PSObject -Property @{
             Name = $vmguest.name
             Label = $_.DeviceInfo.Label
             OS = $vmguest.Guest.GuestFullName
             @{N="ACCESS";E={$CurrentSession=New-SSHSession -ComputerName $_.Name -AcceptKey Credential $creds ;(Invoke-SSHCommand -SSHSession $CurrentSession -Command "echo YES" -OutVariable result).output}}
          }
       }
    }

你能指导我如何做到这一点吗?非常感谢您!

标签: powershellpowerclivcenterwindows-dev-center

解决方案


推荐阅读