Rouven H
Rouven H

Reputation: 71

Powershell - Use a "Contains"/"Match" function for hash maps

i wanna check if the following letters in the following words exists. My code is:

$testString="Word"
$illegalCharacter =@{Warning="a","b";Error="c","d"}

if($testString -match $illegalCharacter.Error){
Write-Host "WORKS!"
}

I guess "-contains" only works with Arrays - not Hash Maps. But why do this dont work?

Thanks :)

Upvotes: 2

Views: 217

Answers (4)

sodawillow
sodawillow

Reputation: 13176

EDIT: I wrongly used -contains here first, but -match is what we want.

Another approach:

$testString = "Word"

$illegalCharacter = @{
    Warning = "a", "b"
    Error   = "c", "d"
}

if ($testString -match ($illegalCharacter.Error -join "|")) {
    Write-Host "WORKS!"
}

This build a string (example for Error: "c|d") that is parsed as a regex meaning either character c or d

Upvotes: 1

AdminOfThings
AdminOfThings

Reputation: 25001

If this is a case-sensitive search, then Split(char[]) will be a concise solution.

$testString="Word"
$illegalCharacter =@{Warning=@("a","b");Error= @("c","d")}
if ($teststring.Split($illegalCharacter.Error).Count -gt 1) {
    Write-Host "WORKS!"
}

If you want to use the -match operator or -cmatch (case-sensitive match) operator, you will need to create a regex expression that includes alternations (|).

$testString="Word"
$illegalCharacter =@{Warning=@("a","b");Error= @("c","d")}
$regex = ($illegalcharacter.Error |% { [regex]::Escape($_) }) -join '|'
if ($teststring -match $regex) {
    Write-Host "WORKS!"
}

The regex | character performs an OR. In this case, it will attempt to match c and alternatively d if c does not match. Special regex characters need to be escaped if you to match them literally. Regex.Escape(String) escapes regex characters automatically.

Upvotes: 1

marsze
marsze

Reputation: 17064

You would have to split up the string first to validate each character. You can do that with .ToCharArray()

My suggestion:

# Will throw for the first illegal character in the word
$testString.ToCharArray() | where { $illegalCharacter.Error -eq $_ } | foreach {
    throw "Illegal character: $_"
}

Upvotes: 1

f6a4
f6a4

Reputation: 1782

You have to use a little bit different approach:

$testString="Word"
$illegalCharacter =@{Warning=@("a","b");Error= @("c","d")}

$illegalCharacter.Error | ForEach-Object { 
    if( $testString.Contains( $_ ) ) {
        Write-Host "WORKS!"; break 
    }
}  

Upvotes: 2

Related Questions