循环问题 - 远程服务器

时间:2015-06-15 17:40:24

标签: powershell

我写了一个小脚本,从一些远程服务器上获取一些基本信息。但我的输出有点奇怪。我相信我的问题在于我的$DRIVE功能。

代码:

$serversList = 'svr01.xxx.com', 
               'svr03.xxx.com', 
               'svr05.xxx.com', 
               'svr06.xxx.com', 
               'svr08.xxx.com'
               #End of Server List

Write-Output "Start of Hal0 `n";

ForEach ($server in $serversList) {
    $OS = (Get-WmiObject -class Win32_OperatingSystem).Caption
    $SYSNAME = (Get-WmiObject -class Win32_LogicalDisk -ComputerName $server).SystemName
    $DRIVE = {
        Get-WmiObject -Class Win32_LogicalDisk -ComputerName $server | 
            Where-Object {$_.DriveType -eq 3} |
            Select-Object DeviceID, Description,`
                @{"Label"="DiskSize(GB)";"Expression"={"{0:N}" -f ($_.Size/1GB) -as [float]}}, `
                @{"Label"="FreeSpace(GB)";"Expression"={"{0:N}" -f ($_.FreeSpace/1GB) -as [float]}} |
            FT -AutoSize
    }
    $server + ' | ' + $SYSNAME + ' | ' + $OS + ' | ' 
}

Write-Output "`n End of Hal0";

结果:

Start of Hal0 

svr01.xxx.com | SVR01 SVR01 SVR01 SVR01 | Mic
rosoft Windows 8.1 Enterprise | 
svr03.xxx.com | SVR03 SVR03 SVR03 SVR03 | Mic
rosoft Windows 8.1 Enterprise | 
svr05.xxx.com | SVR05 SVR05 SVR05 SVR05 | Mic
rosoft Windows 8.1 Enterprise | 
svr06.xxx.com | SVR06 SVR06 SVR06 SVR06 | Mic
rosoft Windows 8.1 Enterprise | 
svr08.xxx.com | SVR08 SVR08 SVR08 SVR08 | Mic
rosoft Windows 8.1 Enterprise | 

 End of Hal0

我希望我的结果将是5台服务器中每台服务器的干净系统全名,系统短名称,操作系统,硬盘空闲/已用空间。

svr08.xxx.com | svr08 | Windows 8 | C: 1111 MB Free/500 MB Used, E: 11 MB Free/10 MB Used.

1 个答案:

答案 0 :(得分:2)

您永远不会在任何地方输出$DRIVE,并且$DRIVE的表达式不应该首先出现在脚本块中。计算机名称重复多次,因为您获得每个逻辑磁盘对象的SystemName属性。此外,$OS获取本地计算机的操作系统名称,而不是远程计算机。

将您的代码更改为以下内容:

$serversList | ForEach-Object {
    $os    = Get-WmiObject -Class Win32_OperatingSystem -Computer $_
    $disks = Get-WmiObject -Class Win32_LogicalDisk -Computer $_ |
             Where-Object {$_.DriveType -eq 3} |
             ForEach-Object {
                 '{0} {1:D} MB Free/{2:D} MB Used' -f $_.DeviceID,
                     [int]($_.FreeSpace/1GB), [int]($_.Size/1GB)
             }

    New-Object -Type PSCustomObject -Property @{
      'FQDN'            = $_
      'ServerName'      = $os.PSComputerName
      'OperatingSystem' = $os.Caption
      'Disks'           = $disks -join ', '
    }
} | Export-Csv 'C:\output.csv' -Delimiter '|' -NoType

如果您希望输出回显而不是写入文件,请使用ConvertTo-Csv而不是Export-Csv

附录:如果要在数据库中导入输出文件,请使用逗号作为CSV的字段分隔符,并将磁盘信息与其他字符一起加入:

$serversList | ForEach-Object {
    ...
    New-Object -Type PSCustomObject -Property @{
      'FQDN'            = $_
      'ServerName'      = $os.PSComputerName
      'OperatingSystem' = $os.Caption
      'Disks'           = $disks -join '|'
    }
} | Export-Csv 'C:\output.csv' -NoType