In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in $arrayOfStringsNotInterestedIn
.
What is the syntax for this?
Get-Content $filename | Foreach-Object {$_}
If you want to know in PowerShell if a string contains a particular string or word then you will need to use the -like operator or the . contains() function. The contains operator can only be used on objects or arrays just like its syntactic counterpart -in and -notin .
The PowerShell string is simply an object with a System. String type. It is a datatype that denotes the sequence of characters, either as a literal constant or some kind of variable. A String can be defined in PowerShell by using the single or double-quotes. Both the strings are created of the same System.
To include the double quotes inside of the string, you have two options. You can either enclose your string in single quotes or escape the double quotes with a symbol called a backtick. You can see an example of both below of using PowerShell to escape double quotes. Notice that "string" now includes the double quotes.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { ` if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With