using powershell like awk to get the console user

大憨熊 提交于 2020-01-05 04:06:48

问题


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                      

回答1:


.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]



回答2:


As others have suggested try the following

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

Or you could try

$consoleuser = $ENV:username



回答3:


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



回答4:


Try

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

More useful stuff here



来源:https://stackoverflow.com/questions/40250376/using-powershell-like-awk-to-get-the-console-user

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!