powershell - 输出中的 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)}}
解决方案
也总是可以选择自己编写格式函数。可能类似于以下内容:
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
推荐阅读
- excel - 如何在Excel VBA中将数字放入数据+时间
- html - 如何使这些图像保持在“网格”中?
- google-sheets - 如何将 Excel 公式转换为 Google 表格?
- android - 从第三方应用程序中提取应用程序链接 (URI)
- java - Java 线程:运行方法不读取实例方法
- flutter - 如何从另一个类中定义的平面按钮的 onPressed 调用主类中定义的方法('_MyHomePageState()')?
- android - 每当将数据添加到 firebase 实时数据库时,它都会打印所有以前的数据
- python - 创建不可更改的图像片段数组
- python - 根据其他列的值在列中设置相同的值
- macos - 无法构建 WebKitGTK:缺少 ICU 库但无法安装它们