代码之家  ›  专栏  ›  技术社区  ›  Rod

如何添加计算列以获取服务powershell输出

  •  0
  • Rod  · 技术社区  · 11 月前

    我想在 get-service 根据名称输出。举个例子,我想拿 Status 列并将其子字符串化,以显示名为的新计算机列中的前3个字符 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
    
    

    enter image description here

    1 回复  |  直到 11 月前
        1
  •  1
  •   mklement0    11 月前

    要按照要求回答您的问题(抛开内部不一致),请使用 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] .