我想在输出中的类轮开头添加一个星号:
$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/