【问题标题】:How to get the value of a particular propery from the result of a powershell command如何从 powershell 命令的结果中获取特定属性的值
【发布时间】:2013-12-17 20:48:44
【问题描述】:

我有一个变量 $ results ,它的值是:

SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 rdp-tcp#1         account17                 7  Active  rdpwd

我想单独获取 ID 的值并在不同的查询中使用它。

我尝试了以下方法:

1.$idValue = @($result | %{ $_.ID }) - 但它没有获得价值。

2.$result |Select -ExpandProperty ID - 我收到错误“选择对象:找不到属性“ID”。”

如何从结果中单独获取属性ID的值?

【问题讨论】:

  • 你运行什么命令来得到你的初始结果?
  • 这是我尝试过的命令 - $result = Query Session account17 /server:localhost 和 $result = qwinsta account17 /SERVER:localhost

标签: powershell


【解决方案1】:

qwinsta/query 命令的输出是字符串,而不是对象,因此没有要打印的属性 ID。如果要将字段作为属性,则需要将字符串转换为对象:

query session | ? { $_ -match '^[ >](\S+) +(\S*?) +(\d+) +(\S+)' } |
  select @{n='Service';e={$matches[1]}},
         @{n='Username';e={$matches[2]}}, 
         @{n='ID';e={$matches[3]}},
         @{n='Status';e={$matches[4]}} | % {
  $_.ID
}

或者,如果您只对 ID 感兴趣,您可以像这样进行正则表达式替换:

$account = 'account17'
$pattern = '^[ >]\S+ +\S*? +(\d+) +\S+.*'

(query session $account | select -Skip 1) -replace $pattern, '$1'

【讨论】:

    【解决方案2】:

    这是正确引用单个属性的格式。我没有看到您创建 RDP $result 的命令,所以我将举例说明 get-process,用 () 封装它,并在末尾添加 ().ID。适用于任何属性,而不仅仅是.ID

    (get-process | where {$_.Name -eq "Powershell"}|select ID).ID
    # or
    $MYID = (get-process | where {$_.Name -eq "Powershell"}|select ID).ID
    $MYID
    

    【讨论】:

    • 我尝试了以下方法: $rs = (qwinsta account17 /SERVER:localhost|select ID).ID; $rs and $result = (Query Session account17 /server:localhost | select ID).ID; $结果。但没有显示输出。
    【解决方案3】:

    另一个选项是-split:

    一种解决方案,使用 V4:

    ($result).ForEach({($_ -split '\s+')[2]}) -match '\d'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多