Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Select-String -pattern -notMatch

I have lines -

echo $LocalAdmins
    Administrator
    Domain-Administrator
    daemon
    SomeUser
  • Line 1-3 should be same although there could be situation where Domain-Administrator doesn't exist so simply counting lines won't help because User might hide in 3rd line.

  • Line 4 string changes, there could be more than 4 lines either as well as no Line 4 at all.

  • I'm not sure yet if lines change their position or not.

I need to get string that is -notMatch "Administrator", "Domain-Administrator", "daemon". I.e., I need user names that are in this list.

Is there a way to use more than one -notMatch with -and or ()? Currently I'm stuck with code that use only one -notMatch. And I can't use -Match because there could be 2+ users in the list.

$LocalAdmins | Select-String -pattern "Administrator" -notMatch
like image 953
Phoneutria Avatar asked Aug 12 '13 09:08

Phoneutria


People also ask

What is select-String in PowerShell?

Select-String uses the Path parameter with the asterisk ( * ) wildcard to search all files in the current directory with the file name extension . txt . The Pattern parameter specifies the text to match Get-. Select-String displays the output in the PowerShell console.

Does PowerShell have grep?

When you need to search through a string or log files in Linux we can use the grep command. For PowerShell, we can use the grep equivalent Select-String . We can get pretty much the same results with this powerful cmdlet. Select-String uses just like grep regular expression to find text patterns in files and strings.

What does the command @() mean in PowerShell?

In PowerShell V2, @ is also the Splat operator. PS> # First use it to create a hashtable of parameters: PS> $params = @{path = "c:\temp"; Recurse= $true} PS> # Then use it to SPLAT the parameters - which is to say to expand a hash table PS> # into a set of command line parameters.


2 Answers

Like this?

$LocalAdmins | select-string -Pattern 'Administrator|daemon' -NotMatch | select -expa line

-pattern accepts REGEX. You can use the | ( or regex operator ) to add others words to fit your needs.

like image 197
CB. Avatar answered Sep 28 '22 04:09

CB.


Assuming that $LocalAdmins is an array you could do this:

$exclude = 'Administrator', 'Domain-Administrator', 'daemon'
$LocalAdmins | Where-Object { $exclude -notcontains $_ }
like image 32
Ansgar Wiechers Avatar answered Sep 28 '22 03:09

Ansgar Wiechers