Split text by columns in PowerShell

后端 未结 12 2122
猫巷女王i
猫巷女王i 2020-11-28 15:37

I\'m a PowerShell novice (Bash is my thing normally) who\'s currently trying to obtain qwinsta output to show who is logged in as an \'rdpwd\' (rdesktop) user so that I can

12条回答
  •  猫巷女王i
    2020-11-28 16:12

    Some of the answers here commendably try to parse the input into objects, which, however, is (a) a nontrivial effort and (b) comes at the expense of performance.

    As an alternative, consider text parsing using PowerShell's -split operator, which in its unary form splits lines into fields by whitespace similar to the standard awk utility on Unix platforms:

    On Windows, if you first install an awk port such as Gawk for Windows, you could invoke awk directly, as demonstrated in Ed Morton's answer. On Unix (using PowerShell Core), awk is available by default.
    The solution below is similar to Ed's, except that it won't perform as well.

    qwinsta | % { if (($fields = -split $_)[4] -eq 'rdpwd') { $fields[1] } }
    
    • -split $_ splits the input line at hand ($_) into an array of fields by runs of whitespace, ignoring leading and trailing whitespace.

    • (...)[4] -eq 'rdpwd' tests the 5th field (as usual, indices are 0-based) for the value of interest.

    • In case of a match, $fields[1] then outputs the 2nd field, the (assumed to be nonempty) username.

提交回复
热议问题