Frage

I have recently switched some scripts from using Powershell Get-content to streamreader- everything is now greatly faster however I am having a problem with case sensitivity being in place on searches.

I did see another post on stackoverflow but couldn't work out what to change (Newbie!) so hoping someone can advise.

An example of my script is

$fullname = Get-Item c:\file.txt
$sr = New-Object System.IO.StreamReader("$fullName")
while (($line = $sr.ReadLine()) -ne $null) {
if ($line.contains("London")) { "$line" | add-content c:\results.txt}

I've read that StringComparison.CurrentCultureIgnoreCase somewhere in the above might help - Help!

War es hilfreich?

Lösung

Well, you are using the .NET method contains. It's easy to get what you want. So,

$line.contains("London") 

is case-sensitive but

$line -contains "London"

is not. This may explain it better:

PS C:\> "london".contains("London")
False
PS C:\> "london" -contains "London"
True

Example:

PS C:\> cat c:\temp\a.txt
Londonnn
london
New York
hello
world

PS C:\> $sr = new-object System.io.streamreader(get-item C:\Temp\a.txt)
PS C:\> while ($line = $sr.readline()) { if ($line -contains "London"){ $line} }
london

Update: -Contain would expect 'exact' word regardless of case. You might want to use -match instead for your use case. See the difference:

PS C:\> while ($line = $sr.readline()) { if ($line -match "London"){ $line} }
Londonnn
london
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top