首页 > 解决方案 > 输出中的 PowerShell 空白

问题描述

当我在脚本中一个接一个地运行两个命令时,我经常会出现很大的差距,正如你可以看到这两个命令(我用“;”将它们连接起来,所以可以将问题视为单行,它只是 aGet-Netipaddress后跟 a gwmi) 他们最终之间有三行差距。有时我希望输出中包含更紧凑的信息。有没有办法告诉 PowerShell 停止在输出之间引入巨大的差距?

Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex ; gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}}

标签: powershellconsoleoutput

解决方案


也总是可以选择自己编写格式函数。可能类似于以下内容:

function Format-TableCompact {
    [CmdletBinding()]  
    Param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] 
        [PsObject]$InputObject,

        [switch]$AppendNewline
    )
    # If the data is sent through the pipeline, use $input to collect is as array
    if ($PSCmdlet.MyInvocation.ExpectingInput) { $InputObject = @($Input) }
    # or use : $InputObject = $Input | ForEach-Object { $_ }

    $result = ($InputObject | Format-Table -AutoSize | Out-String).Trim()
    if($AppendNewline) { $result += [Environment]::NewLine }
    $result
}

这会将对象作为表格输出,没有任何前导或尾随换行符,因此称为 using

Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex | Format-TableCompact
gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}} | Format-TableCompact

它将直接将两张桌子相互撞击。

但是,在这种情况下,我会选择在表之间至少有一个换行符,所以我会使用-AppendNewline第一个表上的开关来输出:

Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex | Format-TableCompact -AppendNewline
gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}} | Format-TableCompact

推荐阅读