简体   繁体   中英

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.

I tried the following ways :

1. $idValue = @($result | %{ $_.ID }) - but it was not getting the value.

2. $result |Select -ExpandProperty ID - I was getting the error 'Select-Object : Property "ID" cannot be found.'

How to get the value of the property ID alone from the result?

The output of the qwinsta / query commands are strings, not objects, so there isn't a property ID to print. 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:

$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. Works with any property, not just.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:

One solution, using V4:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM