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
解决方案
为了使您的变量对 powershell 有意义,您需要替换
$result = @($comp,$version,$user)
和
New-Object psobject -Property @{'ComputerName'=$comp;
'Version'=$version;
'User'=$user}
原因是,您没有定义每个变量的属性,只是定义它是变量,因此您得到的输出肯定看起来很奇怪。不要 decalare $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
推荐阅读
- bash - 将文本文件集的内容复制到其他文本文件集
- c++ - 将 $(location) 传递给 Bazel --test_arg
- python - Python 3 中的服务目录
- kubernetes - Kubernetes 节点未就绪:ContainerGCFailed / ImageGCFailed 上下文期限已超过
- php - SEO 问题 Google 将我的网站 URL 编入索引两次
- c - 循环中的表格未正确显示数据
- git - 在推送到 github 时,! [rejected] master -> master (fetch first) error: failed to push some refs to "
" - ajax - 如何正确地将 ajax 函数重写为 Reactjs 等效项
- excel - Excel iso 8601 时间戳减去 2 小时转换
- google-bigquery - BigQuery _TABLE_SUFFIX 为空/缺少表