Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select string to display only a certain part of a returned line

I am trying to get piped select-string commands in Powershell to return only what I'm searching for, plus some extra information at the end. Here is what I have so far:

PS H:\> gwmi win32_LoggedOnUser -computer server | select-string -pattern "domain" | select-string -pattern "Admin" -NotMatch

\\server\root\cimv2:Win32_LoggedOnUser.Antecedent="\\\\.\\root\\cimv2:Win32_Account.Domain=\"domain\",Name=\"user1\"",Dependent="\\\\.\\root\\cimv2:Win32_LogonSession.LogonId=\"44946387\""
\\server\root\cimv2:Win32_LoggedOnUser.Antecedent="\\\\.\\root\\cimv2:Win32_Account.Domain=\"domain\",Name=\"user2\"",Dependent="\\\\.\\root\\cimv2:Win32_LogonSession.LogonId=\"41485153\""
\\server\root\cimv2:Win32_LoggedOnUser.Antecedent="\\\\.\\root\\cimv2:Win32_Account.Domain=\"domain\",Name=\"user3\"",Dependent="\\\\.\\root\\cimv2:Win32_LogonSession.LogonId=\"46401036\""
\\server\root\cimv2:Win32_LoggedOnUser.Antecedent="\\\\.\\root\\cimv2:Win32_Account.Domain=\"domain\",Name=\"user4\"",Dependent="\\\\.\\root\\cimv2:Win32_LogonSession.LogonId=\"40161073\""
\\server\root\cimv2:Win32_LoggedOnUser.Antecedent="\\\\.\\root\\cimv2:Win32_Account.Domain=\"domain\",Name=\"user5\"",Dependent="\\\\.\\root\\cimv2:Win32_LogonSession.LogonId=\"46557830\""

So I've got what I'm looking for but I want to shorten up what the command actually shows me. Preferably I would like to see only:

Domain\user1
Domain\user2

But I do not know how to do this. The closest I have come is by piping another command 'Select Matches' onto the end. I have read that regex may be the answer to my troubles.

Thanks in advance for any help.

like image 899
Tekz08 Avatar asked Nov 18 '25 09:11

Tekz08


1 Answers

Please use something like below:

(gwmi win32_LoggedOnUser) | %{[void]($_.Antecedent -match 'Domain="(\w+)",Name="(\w+)"'); "{0}\{1}" -f $matches[1],$matches[2]}

Avoid using so many select-string - that is like bash with all the grep, sed, awk, cut voodoo which I believe Powershell avoids with high fidelity objects. Try to use the Objects and their properties as much as possible. Yes it is not always possible to use them and we resort to select-string or other string manipulations, but try to avoid them till the last possible step. Makes Powershell programming neat, simple and bug-free IMO.

like image 185
manojlds Avatar answered Nov 20 '25 04:11

manojlds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!