在作业中返回Powershell阵列

时间:2018-10-23 23:21:51

标签: arrays 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

1 个答案:

答案 0 :(得分:0)

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

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

使用

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

原因是,您没有定义每个变量的属性,只是因为它是变量,所以您肯定会得到的输出看起来很奇怪。不要对$ result进行贬值,因为它是作业中的变量,并且它们是powershell的单独实例。这样比较容易。

为了完成输出到gridview ,您需要将receive-job输送到out-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