Home > Blockchain >  Powershell - Excluding Word on a Text File and Print the Output
Powershell - Excluding Word on a Text File and Print the Output

Time:11-26

I am trying to create a script to list all the users with local admin rights on a machine. The output will be saved to a txt file. Users that matches on the holder $User1, $User2, and $User3 will be excluded on the output.

Here's my code:

$User1 = "Administrator"
$User2 = "Admin1"
$User3 = "Admin2"

$LocalAdmin = Get-Content C:\AdminUsers.txt | Select-String -Pattern "$User1" -NotMatch | Select-String -Pattern "$User2" -NotMatch | Select-String -Pattern "$User3" -NotMatch

echo $LocalAdmin

The output shows like this:

Members

-------------------------------------------------------------------------------
User1
User2
The command completed successfully.

How can I print only the user not the entire result like the below?

User1
User2

Thank you,

CodePudding user response:

I found the right command now. Here it is:

net localgroup Administrators >> C:\AdminUsers.txt
$User1 = "Administrator"
$User2 = "Admin1"
$User3 = "Admin2"
$Text1 = "Members"
$Text2 = "-------------------------------------------------------------------------------"
$Text3 = "The command completed successfully."
(gc C:\AdminUsers.txt ) | ? {$_.trim() -ne "" } | set-content C:\AdminUsers1.txt 
$LocalAdmin = Get-Content C:\AdminUsers1.txt | Select-String -Pattern "$User1", "$User2", "$User3", "$Text1", "$Text2", "$Text3" -NotMatch 
echo $LocalAdmin
del C:\AdminUsers.txt
del C:\AdminUsers1.txt 

Thanks for the help everyone.

CodePudding user response:

I agree with Lee-Dailey that it would be easier to use Get-LocalGroupMember, but if you really want to use net localgroup Administrators and store the result in a text file, I would use:

$users = ((Get-Content -Path 'C:\Administrators.txt' -Raw).Trim() -split '(?m)^- ')[1] -split '\r?\n' | Select-Object -SkipLast 1

However, there should be no need to first write to a file if you do all from memory:

$users = ((net localgroup Administrators | Where-Object { $_ -match '\S' }) -join "`r`n" -split '(?m)^- ')[1] -split '\r?\n' | Select-Object -SkipLast 1

or

$users = (((net localgroup Administrators) -join "`r`n").Trim() -split '(?m)^- ')[1] -split '\r?\n' | Select-Object -SkipLast 1
  • Related