PowerShell 在 Get-ComputerInfo 的行输出开头添加破折号

标签 powershell

我想在输出中的类轮开头添加一个星号:

$SYSLST1 = "OsName","OsVersion","TimeZone","CsName"
$X = (Get-ComputerInfo -Property $SYSLST1 | Format-List | Out-String).Trim()
$Y = ForEach ($Z in $X){
$Z.insert(0,"  * ")
}
Write-Host $Y

但它只执行第一行:

  * OsName    : Microsoft Windows Server 2016 Standard
OsVersion : 10.0.14393
TimeZone  : (UTC-05:00) Eastern Time (US & Canada)
CsName    : SIS-2016-INT-ST

最佳答案

您需要 -Stream 开关来指示 Out-String输出单行 - 默认情况下,您将得到多行字符串。

此外,您还可以在 -replace operator 的帮助下简化字符串插入任务。 :

(
  Get-ComputerInfo -Property $SYSLST1 | Format-List | Out-String -Stream
).Trim() -ne '' -replace '^', '  * '
  • -ne '' 过滤掉在所有输出行上调用 .Trim() 所产生的空行(通过 member-access enumeration )。

  • -replace '^', ' * ',用指定的字符串替换字符串的开头 (^),实际上将其插入到每行的开头。

一般来说,请注意 Format-* cmdlet 输出对象的唯一目的是向 PowerShell 的输出格式化系统提供格式化指令(在您的情况下由Out-String) - 请参阅 this answer .

简而言之:使用 Format-* cmdlet 格式化数据用于显示,而不是用于后续编程处理 .

关于PowerShell 在 Get-ComputerInfo 的行输出开头添加破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68778381/

相关文章:

powershell - DynamoDB API 过滤扫描不返回任何结果

regex - 背后的Powershell反向引用

debugging - 有没有办法在错误时进入调试器?

powershell - 检查 powershell 版本并根据版本运行函数

shell - If语句-如何检查路径是否包含文件

powershell - Azure Batch 容器配置中的 Azure 容器注册表的 AD 服务主体?

windows - 在远程 Powershell session 中执行交互式命令不起作用

powershell - 如何通过 Powershell 在 Windows 中断开 VPN

arrays - PowerShell 通过引用函数传递两个数组

.net - 相当于 C#'s "在 powershell 中使用“关键字?