Powershell脚本在第二个函数上输出空白

我正在写一个大脚本来扫描AD中计算机的WMI信息。 我有diskinfo,raminfo和videocardinfofunction,其中磁盘和video卡具有类似的输出风格。 问题是,根据脚本运行的顺序,要么输出为空。 这是两个function:

函数Get-DiskInfo {

$disk = Get-WMIObject Win32_Logicaldisk -ComputerName $computer | Select @{Name="Computer";Expression={$computer}}, DeviceID, @{Name="SizeGB";Expression={$_.Size/1GB -as [int]}}, @{Name="FreeGB";Expression={[math]::Round($_.Freespace/1GB,2)}} Write-Host $Computer $disk 

}

和:

函数Get-VRamInfo {

 $vram = Get-WmiObject win32_videocontroller -ComputerName $computer | Select @{Name="Computer";Expression={$computer}}, @{Name="VideoRAM";Expression={$_.adapterram / 1MB}}, Name Write-Host $computer $vram 

}

一个会得到预期的输出,但稍后在脚本中运行的输出将仅输出计算机名称,但不输出信息

这里是完整的脚本: https : //gist.github.com/ErkkaKorpi/f1b10a62ac79763fa38082b6c25e8f1b

可能是什么问题呢?

出于某些不清楚的原因, Write-Output cmdlet会记住自定义对象的第一个/上一个用法的属性,以便用于下一次使用,甚至应用于另一个(不同定义的)自定义对象。 不幸的是,我不知道如何重置记住的属性。

有一个解决方法 :使用Format-Table如下。 (请注意,为了更好地理解,我在Get-VRamInfo添加了SizeGB注释属性。)

 Function Get-DiskInfo { $disk = Get-WMIObject Win32_Logicaldisk -ComputerName $computer | Select-Object @{Name="Computer";Expression={$computer}}, DeviceID, @{Name="SizeGB";Expression={$_.Size/1GB -as [int]}}, @{Name="FreeGB";Expression={[math]::Round($_.Freespace/1GB,2)}} #Write-Host $Computer -ForegroundColor Magenta $disk } Function Get-VRamInfo { $vram = Get-WmiObject win32_videocontroller -ComputerName $computer | Select-Object @{Name="Computer";Expression={$computer}}, @{Name="VideoRAM";Expression={$_.adapterram / 1MB -as [int]}}, @{Name="SizeGB";Expression={$_.adapterram/1GB -as [int]}}, Name #Write-Host $computer -ForegroundColor Cyan $vram } $computer = '.' "`nshrunk output #1" Get-VRamInfo Get-DiskInfo "`nfull output" Get-VRamInfo | Format-Table Get-DiskInfo | Format-Table "`nshrunk output #2" Get-DiskInfo Get-VRamInfo 

输出

 PS D:\PShell> D:\PShell\SF\884809.ps1 shrunk output #1 Computer VideoRAM SizeGB Name -------- -------- ------ ---- . 2048 2 NVIDIA GeForce GT 740 . 111 . 932 . 0 full output Computer VideoRAM SizeGB Name -------- -------- ------ ---- . 2048 2 NVIDIA GeForce GT 740 Computer DeviceID SizeGB FreeGB -------- -------- ------ ------ . C: 111 58.06 . D: 932 856.47 . E: 0 0 shrunk output #2 Computer DeviceID SizeGB FreeGB -------- -------- ------ ------ . C: 111 58.06 . D: 932 856.47 . E: 0 0 . 2 

Write-Output cmdlet通常在脚本中用于在控制台上显示string和其他对象。 但是,由于缺省行为是在pipe道末尾显示对象,因此通常不需要使用该cmdlet。
例如, Get-Process | Write-Output Get-Process | Write-Output相当于Get-Process

看看你的脚本,你没有定义$computer ,所以它应该直接错误的任何这些function。 定义后,我可以确认第二个函数返回适配器就好了,当在Windows 10 1703上使用:

在这里输入图像说明

从输出中可以看到, $vram已经包含了你的计算机名,所以你可能想跳过Write-Host $Computer部分。

正如我所看到的,您似乎在同时检查大量计算机,因此您可以查看允许并行执行任务的PowerShell Workflows,因此您可以在ForEach -Parallel循环中使用您的函数,并让它们执行得多更快。