1

I basically want to use powershell and get the console user like

"query session | findstr console | awk '{print $2}'"

but not using awk, but I can't get it to work.

$out = query session | findstr console # good
$consoleuser = $out.split('\s+')[1]    # doesn't work

$out looks something like:

>console           joe                       2  Active                      

$consoleuser ends up being:

ole           joe                       2  Active                      
js2010
  • 23,033
  • 6
  • 64
  • 66

4 Answers4

4

As others have suggested try the following

$out = query session | findstr console
$consoleuser = $($out -split('\s+'))[1]

Or you could try

$consoleuser = $ENV:username
  • ++ for the `$env:USERNAME` tip; note that there's no need for `$(...)`, the subexpression operator, when simple parentheses (`(...)`) will do; also, while using _method_-invocation syntax (`-split(…)`) with the `-split` _operator_ happens to work in this case, it is best avoided. Thus: `$consoleuser = ($out -split '\s+')[1]` – mklement0 Oct 25 '16 at 22:59
  • 1
    Thanks for both of the suggestions, I'll do that in the future. – armorall171 Oct 26 '16 at 03:08
3

.Split() is a .Net string method, it doesn't use regexes. -split is the PowerShell operator and uses regexes.

And calling out to findstr is usable, but there's no need to leave PS to use it. e.g.

$out = query session | Where {$_ -match 'console'}
$consoleuser = ($out -split '\s+')[1]

((query session) -match 'console' -split '\s+')[1]
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
1

To complement TessellatingHeckler's helpful answer with a further optimization (but note that armorall171's helpful recommendation to simply use $env:USERNAME may be all you need):

(-split ((query session) -match '^>console'))[1]

Output from external command query session is returned as an array of strings by PowerShell, and the -match operator filters that array down to only the matching elements (just 1 line in this case).

The -split operator has a unary form whose behavior is similar to awk's default field-parsing behavior:

It splits the input into array elements by runs of whitespace, ignoring leading and trailing whitespace.

Example:

> -split "  ab  `t  `t    cde `n `n efgh       "
ab
cde
efgh
Community
  • 1
  • 1
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Try

($out -Split '\s+')[1]

More useful stuff here

Dinesh
  • 4,437
  • 5
  • 40
  • 77