[英]How to get the value of a particular propery from the result of a powershell command
I have a variable $ results which has the value : 我有一个变量$结果,其值是:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
rdp-tcp#1 account17 7 Active rdpwd
I want to get the value of ID alone and use it in a different query. 我想单独获取ID的值并在其他查询中使用它。
I tried the following ways : 我尝试了以下方法:
1. $idValue = @($result | %{ $_.ID })
- but it was not getting the value. 1. $idValue = @($result | %{ $_.ID })
-但未获取值。
2. $result |Select -ExpandProperty ID
- I was getting the error 'Select-Object : Property "ID" cannot be found.' 2. $result |Select -ExpandProperty ID
我收到错误“选择对象:找不到属性“ ID””。
How to get the value of the property ID alone from the result? 如何从结果中单独获取属性ID的值?
The output of the qwinsta
/ query
commands are strings, not objects, so there isn't a property ID
to print. qwinsta
/ query
命令的输出是字符串,而不是对象,因此没有要打印的属性ID
。 You need to transform the strings into objects if you want the fields as properties: 如果要将字段作为属性,则需要将字符串转换为对象:
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
}
Or, if you're just interested in the ID, you could do a regular expression replacement like this: 或者,如果您仅对ID感兴趣,则可以执行如下正则表达式替换:
$account = 'account17'
$pattern = '^[ >]\S+ +\S*? +(\d+) +\S+.*'
(query session $account | select -Skip 1) -replace $pattern, '$1'
This is the format to refer to a single property properly. 这是正确引用单个属性的格式。 I don't see your command to create your RDP $result, so I'll example get-process, encapsulate it with () and tack an ().ID to the end. 我看不到用于创建RDP $ result的命令,因此我将以get-process为例,将其封装为(),然后将().ID附加到最后。 Works with any property, not just.ID 适用于任何属性,而不仅仅是.ID
(get-process | where {$_.Name -eq "Powershell"}|select ID).ID
# or
$MYID = (get-process | where {$_.Name -eq "Powershell"}|select ID).ID
$MYID
Another option is -split: 另一个选项是-split:
One solution, using V4: 使用V4的一种解决方案:
($result).ForEach({($_ -split '\s+')[2]}) -match '\d'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.