我想在 get-service 根据名称输出。举个例子,我想拿 Status 列并将其子字符串化,以显示名为的新计算机列中的前3个字符 Name 2 .
get-service
Status
Name 2
尝试了以下操作,但没有得到预期的行为:
# Get all services $services = Get-Service -Name BITS, appinfo # Add a computed column $servicesWithComputedColumn = $services | Select-Object *, @{Name='ServiceType'; Expression={ if ($_.StartType -eq 'Automatic') { 'rsAuto' } else { 'rsManual' } }} # Display the result $servicesWithComputedColumn
要按照要求回答您的问题(抛开内部不一致),请使用 calculated property :
Get-Service -Name BITS, appinfo | Select-Object *, @{ Name = 'Name 2' Expression = { $_.Status.ToString().Substring(0, 3) } } | Format-Table Status, Name, 'Name 2', DisplayName
注意需要致电 .ToString() 在 $_.Status 为了执行子字符串操作( .Substring() ),因为 $_.状态 后者是一个实例 [enum] -派生类型,特别是 [System.ServiceProcess.ServiceControllerStatus] .
.ToString()
$_.Status
.Substring()
$_.状态
[enum]
[System.ServiceProcess.ServiceControllerStatus]