【问题标题】:How to imbricate a command inside another command?如何将一个命令覆盖在另一个命令中?
【发布时间】:2017-11-09 08:19:55
【问题描述】:

我有以下 PowerShell 脚本,它允许我收集有关启动脚本所在域的 Windows 服务器上的磁盘和卷的信息:

$ErrorActionPreference = 'SilentlyContinue'

Get-ADComputer -Filter 'OperatingSystem -like "*Server*"' -Properties * |
    Select-Object Name |
    ForEach-Object {
        if (Test-Connection $_.Name -Count 1) {
            Get-WmiObject -Class Win32_LogicalDisk -ComputerName $_.Name -Filter "DriveType=3" | 
                Select-Object PSComputerName, DeviceID, 
                    @{Name="Size /GB";Expression={[math]::Round($($_.Size / 1GB), 2)}},
                    @{Name="Free /GB";Expression={[math]::Round($($_.Freespace / 1GB), 2)}},
                    @{Name="Free %";Expression={[math]::Round($($_.Freespace/$_.Size)*100, 1)}}
        } else {
            Write-Nost $_.Name " Connection Error"
        }
    } |
    sort PSComputerName |
    Format-Table -AutoSize

我得到以下结果:

SRV01 连接错误 SRV02 连接错误 PSComputerName DeviceID Size /GB Free /GB Free % -------------- -------- ------------ --------- -------- 服务器03 C:125,51 105,59 84,1 服务器04 C:24,83 7,38 29,7 服务器05 E:14,65 7,36 50,2 服务器06 C:49,66 29,28 59

我想为每台服务器添加一个包含操作系统的附加列。 我希望此列位于“PSComputerName”列之后的第二位。我怎样才能得到这个结果? 我想我通过在Get-WmiObject -Class Win32_LogicalDisk ... 中添加Get-WmiObject Win32_OperatingSystem | Select-Object caption 来使用嵌套命令,但我不知道要使用哪种语法以及如何将命令覆盖在另一个命令中。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    不要使用 -properties *... 它将检索您在此脚本中不需要的每个填充属性。

    Get-ADComputer 有一个 operatingsystem 属性。

    未测试:

    Get-ADComputer -Filter 'OperatingSystem -like "*Server*"' -Properties OperatingSystem  | ForEach-Object {
        $OS = $_.OperatingSystem
        If (Test-Connection $_.Name -Count 1 -Quiet){
            Get-WmiObject -Class win32_logicalDisk -ComputerName $_.Name -Filter "DriveType=3" | 
            Select-Object pscomputername, @{Name="OS";Expression={$OS}} ,DeviceID,              
                @{Name="Size /GB";Expression={[math]::Round($($_.size / 1GB), 2)}}, 
                @{Name="Free /GB";Expression={[math]::Round($($_.freespace / 1GB), 2)}},
                @{Name="Free %";Expression={[math]::Round($($_.Freespace/$_.Size)*100, 1)}}
        }
        else {
            Write-host $_.Name " Connection Error"
        }
    } | sort pscomputername | Format-Table -AutoSize
    

    【讨论】:

      猜你喜欢
      • 2016-08-19
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 2013-11-08
      • 1970-01-01
      • 2016-08-31
      • 2022-01-24
      相关资源
      最近更新 更多