首页 > 解决方案 > 在作业中返回 Powershell 数组

问题描述

我是 powershell 的新手,我试图让下面的脚本将数据返回到一个数组中,我可以通过管道输出到 Out-Gridview。我似乎无法弄清楚为什么它不起作用。任何帮助,将不胜感激。

$scriptblock = {

  Param($comp)
  IF (Test-Connection $comp -Quiet){
    $user = (Get-WmiObject -Class win32_computersystem -ComputerName $comp | Select-Object username ).Username

    Get-Service -ComputerName $comp -Name "remoteregistry" | start-service -ErrorAction Ignore

    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $comp)
    $vRegKey= $Reg.OpenSubKey("SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{19C7ABD4-4445-48B0-9D02-5A706D080688}")
    $Version = $vRegKey.GetValue("DisplayName")

        Get-Service -ComputerName $comp -Name remoteregistry | stop-service -ErrorAction Ignore

  } ELSE { Write-Host "***$comp ERROR -Not responding***" }
  $result = @($comp,$version,$user) 
}

$comps = get-content -path 'C:\temp\hostnames.txt'
$comps | ForEach-Object {Start-Job -Scriptblock $scriptblock -ArgumentList $_ | Out-Null}
Get-Job | Wait-Job | Receive-Job

$result | Out-GridView

标签: arrayspowershell

解决方案


为了使您的变量对 powershell 有意义,您需要替换

$result = @($comp,$version,$user)

New-Object psobject -Property @{'ComputerName'=$comp;
          'Version'=$version;
          'User'=$user} 

原因是,您没有定义每个变量的属性,只是定义它是变量,因此您得到的输出肯定看起来很奇怪。不要 decalare $result,因为它是作业中的变量,并且它们是 powershell 的单独实例。这种方式比较容易。

为了完成向gridview的输出,您需要通过管道传输receive-jobout-gridview

$comps | ForEach-Object {Start-Job -Scriptblock $scriptblock -ArgumentList $_ | Out-Null}
Get-Job | Wait-Job | Receive-Job | Out-GridView

这是我实际编写脚本的方式....声明$result

$scriptblock = {

  Param($comp)
  IF (Test-Connection $comp -Quiet){
    $user = (Get-WmiObject -Class win32_computersystem -ComputerName $comp | Select-Object username ).Username

    Get-Service -ComputerName $comp -Name "remoteregistry" | start-service -ErrorAction Ignore

    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $comp)
    $vRegKey= $Reg.OpenSubKey("SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{19C7ABD4-4445-48B0-9D02-5A706D080688}")
    $Version = $vRegKey.GetValue("DisplayName")

        Get-Service -ComputerName $comp -Name remoteregistry | stop-service -ErrorAction Ignore

  } ELSE { Write-Host "***$comp ERROR -Not responding***" }
  $script:result += New-Object psobject -Property @{'ComputerName'=$comp;
          'Version'=$version;
          'User'=$user} 
}
$result = $null
$comps = get-content -path 'C:\temp\hostnames.txt'
$comps | ForEach-Object {Start-Job -Scriptblock $scriptblock -ArgumentList $_ | Out-Null}
Get-Job | Wait-Job 

$result | Out-GridView

推荐阅读