Home > OS >  Stripping out all brackets from a string - Powershell
Stripping out all brackets from a string - Powershell

Time:07-25

If I want to split this string into an array and strip out all brackets but only want to split in the dash how would I do it.

$ADUser = "Offline - Server (Win2012)"
This string could potentially be:  "Offline | Server (Win2012)" 
With pipe split!

###This:  
$userdesc = ($ADUser -split ' *[-|] *') -notmatch '[?@]' -replace '^\(|\)$'

##results as:  
Offline   
Server (Win2012

##But I need this:  
Offline  
Server Win2012

##I have tried this to no avail:  
($ADUser -split ' *[-|] *') -notmatch '[?@]' -replace '^\(|\)$|^\s*\(\$'

Any clues or pointers greatly appreciated.

CodePudding user response:

You can use

($ADUser -split "\s*[|-]\s*") | ?{ $_ -notmatch '[?@]' } | %{ $_ -replace '[()]' }

That is

  • ($ADUser -split "\s*[|-]\s*") - splits with a | or - chars enclosed with zero or more whitespaces
  • ?{ $_ -notmatch '[?@]' } - discards all items not containing ? and @
  • %{ $_ -replace '[()]' } - removes the parentheses.
  • Related