将Get-WmiObject脚本的结果格式化为与Get-content.txt文件中的列表匹配



我正在尝试编写一个脚本,该脚本将获取服务器上的驱动器当前驱动器空间,并将其返回到输出文件。

以下是截至目前的脚本:

$ServerName = Get-Content -Path "C:Users*****DesktopTesting Filesserverlist.txt"
Get-WmiObject Win32_LogicalDisk -ComputerName $ServerName -Filter DriveType=3 | Select-Object DeviceID, @{'Name'='Size (GB)'; 'Expression'={Expression'={[string]::Format('{0:NO}',[math]::truncate($_.size / 1GB))}}, @{'Name'='Freespace (GB)'; 'Expression'={[string]::Format('{0:NO}',[math]::truncate($_.freespace / 1GB))}}

Out-file "C:usersxxxxxxdesktoptesting filesserver space results.txt" 

不会写入文本文件;仅显示结果

结果显示设备ID、大小(GB(和可用空间(GB(,除一个问题外没有其他问题。每个驱动器都被列为C:和E:,但不会根据设备名称将它们分开,因此很难判断哪些结果会进入哪个服务器。以下是脚本结果的示例:

DeviceID Size (GB) Freespace (GB)
-------- --------- --------------
C:       58        13
E:       499       499
C:       79        30
E:       799       103

有什么想法吗?

您有一些打字错误和/或语法错误。此外,如果您希望计算机名称PowerShell添加PSComputerName属性:

$ServerName = Get-Content -Path "C:Users*****DesktopTesting Filesserverlist.txt"
Get-WmiObject Win32_LogicalDisk -ComputerName $ServerName -Filter DriveType=3 | 
Select-Object PSComputerName,DeviceID, 
@{'Name'='Size (GB)'; Expression = {[string]::Format('{0:N0}',[math]::truncate($_.size / 1GB))}}, 
@{'Name'='Freespace (GB)'; Expression = {[string]::Format('{0:N0}',[math]::truncate($_.freespace / 1GB))}} |
Out-file "C:usersxxxxxxdesktoptesting filesserver space results.txt"

注意:我更喜欢使用win32_Volume。此外,您应该考虑使用Get-CimInstance而不是Get-WMIObject。后者已被弃用。

更新

这是一个稍微修改过的版本。在这些情况下,我通常使用[Math]::Round()。它将保持数值,使其向右对齐。

$ServerName = Get-Content -Path "C:Users*****DesktopTesting Filesserverlist.txt"
Get-WmiObject Win32_LogicalDisk -ComputerName $ServerName -Filter DriveType=3 | 
Select-Object PSComputerName,DeviceID, 
@{'Name'='Size (GB)'; Expression = { [Math]::Round( ($_.size / 1GB), 0 ) } }, 
@{'Name'='Freespace (GB)'; Expression = { [Math]::Round( ($_.freespace / 1GB), 0 ) } } |
Out-file "C:tempxxxxxxdesktoptesting filesserver space results.txt"

最新更新