Check if a string contains any substring in an array in PowerShell - powershell

I am studying PowerShell. I want to know how to check if a string contains any substring in an array in PowerShell. I know how to do the same in Python. The code is given below:
any(substring in string for substring in substring_list)
Is there similar code available in PowerShell?
My PowerShell code is given below.
$a = #('one', 'two', 'three')
$s = "one is first"
I want to validate $s with $a. If any string in $a is present in $s then return True. Is it possible in PowerShell?

Using the actual variables in the question for simplicity:
$a = #('one', 'two', 'three')
$s = "one is first"
$null -ne ($a | ? { $s -match $_ }) # Returns $true
Modifying $s to not include anything in $a:
$s = "something else entirely"
$null -ne ($a | ? { $s -match $_ }) # Returns $false
(That's about 25% fewer characters than chingNotCHing's answer, using the same variable names of course :-)

($substring_list | %{$string.contains($_)}) -contains $true
should strictly follow your one-liner

For PowerShell ver. 5.0+
Instead of,
$null -ne ($a | ? { $s -match $_ })
try this simpler version:
$q = "Sun"
$p = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
[bool]($p -match $q)
This returns $True if substring $q is in the array of string $p.
Another Example:
if ($p -match $q) {
Write-Host "Match on Sun !"
}

Michael Sorens' code answer works best to avoid the pitfall of partial substrings matching. It just needs a slight regex modification. If you have the string $s = "oner is first", the code would still return true since 'one' would match 'oner' (a match in PowerShell means the second string contains the first string.
$a = #('one', 'two', 'three')
$s = "oner is first"
$null -ne ($a | ? { $s -match $_ }) # Returns $true
Add some regex for word boundary '\b' and the r on 'oner' will now return false:
$null -ne ($a | ? { $s -match "\b$($_)\b" }) # Returns $false

(I know it's an older thread but at least I might help people looking at this in the future.)
Any response given that uses -match will produce incorrect answers.
Example: $a -match $b will produce false negatives if $b is "."
A better answer would be to use .Contains - but it's case sensitive so you'd have to set all strings to upper or lower case before comparing:
$a = #('one', 'two', 'three')
$s = "one is first"
$a | ForEach-Object {If ($s.toLower().Contains($_.toLower())) {$True}}
Returns $True
$a = #('one', 'two', 'three')
$s = "x is first"
$a | ForEach-Object {If ($s.toLower().Contains($_.toLower())) {$True}}
Returns nothing
You could tweak it to return $True or $False if you'd want, but IMO the above is easier.

I'm amazed that in 6 years nobody has given this more simple and readable answer
$a = #("one","two","three")
$s = "one1 is first"
($s -match ($a -join '|')) #return True
So simply implode the array into a string using vertical bar "|" , as this is the alternation (the "OR" operator) in regex.
https://www.regular-expressions.info/alternation.html
https://blog.robertelder.org/regular-expression-alternation/
Also keep in mind that the accepted answer will not search for exact match. If you want exact match you can use the \b (word boundary)
https://www.regular-expressions.info/wordboundaries.html
$a = #("one","two","three")
$s = "one1 is first"
($s -match '\b('+($a -join '|')+')\b') #return False

It is possible to select a subset of strings containing any of the strings like this:
$array = #("a", "b")
$source = #("aqw", "brt", "cow")
$source | where {
$found = $FALSE
foreach($arr in $array){
if($_.Contains($arr)){
$found = $TRUE
}
if($found -eq $TRUE){
break
}
}
$found
}

One way to do this:
$array = #("test", "one")
$str = "oneortwo"
$array|foreach {
if ($str -match $_) {
echo "$_ is a substring of $str"
}
}

Related

Powershell - Matching text from array and string?

I have an array that simply pulls a list of numbers in one long column. I am trying to match it with some data in a string and if it matches, I am wanting it to state Down otherwise it will state Up in the output CSV.
Here is my code: `
IF($RESULTS -like $TEST)
{$Output = "DOWN"
}ELSE{
$OUtput = "UP"
}
`
$RESULTS is the array, and $TEST is the string. If I do -match it works, but -match only pulls single digits so it gives false positives. For example, if there is a 3 in the list as well as 638 it will mark them both as down. None of the other switches seem to work like -eq, -like, etc.
What am I missing please?
Thanks much for any assistance!
EDIT:
Sample of Data in $TEST
2
3
5
Sample of Output of $RESULTS
5
628
Since 5 exists in both, my expected output would be DOWN and everything else would be UP.
It sounds like you have two arrays of numbers, and you want to test if the input array contains at least one of the values in the test array.
You can use Compare-Object, which compares two arrays and indicates which elements are different and, with -IncludeEqual, also which ones are the same:
if (
(Compare-Object -IncludeEqual $RESULTS $TEST).
Where({ $_.SideIndicator -eq '==' }).
Count -gt 0
) {
$Output = "DOWN"
}
else {
$Output = "UP"
}
As an aside:
You can use an if statement as an expression, which means you only need to specify $Output once:
$Output =
IF (<# conditional #>) {
"DOWN"
}
ELSE {
"UP"
}
In PowerShell (Core) 7+, you can use ?:, the ternary conditional operator for a more concise solution:
$Output = <# conditional #> ? 'DOWN' : 'UP'
I would do it by using "foreach". Hope this might be helpful
foreach ($result in $RESULTS){
if ($result -like $Test){
$OUTPUT = "Down"}
else{
$OUTPUT= "UP"}
}
In your edited question you show that variable $TEST is also an array, so in that case you can do
$TEST = 2,3,5
$RESULTS = 5,628
# compare both arrays for equal items
$Output = if ($TEST | Where-Object { $RESULTS -contains $_ }) {"DOWN"} else {"UP"}
$Output
In this case, $Output will be DOWN because both arrays have the number 5
If however variable $TEST contains a multiline string, then first create an array out of that like
$TEST = #'
2
3
5
'#
# convert the string to array by splitting at the newline
$TEST = $TEST -split '\r?\n' -ne ''
$RESULTS = 5,628
# compare both arrays for equal items
$Output = if ($TEST | Where-Object { $RESULTS -contains $_ }) {"DOWN"} else {"UP"}
$Output

How to find a specific text is available in .txt file using powershell

I want to write a PowerShell script where I will give two string values as parameters, It should check the .txt file and should tell whether the strings are available or not in the given file. For example, if I have a list of employees details. I will give the emp_id and emp_name as input. If the name and id exist in that .txt file it should print that. If not it should print the else statement.
Function Empdetails {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory=$true)]$empid,
[Parameter(Mandatory=$true)]$empname)
$path = Get-Content C:\empdetails.txt | Where-Object {$_ -like '*name*'}
if ($path -eq $true) {
Write-Host "Found"
}
else {
Write-Host "Not Found"
}
}
I tried the above code, But it is working. Could you please help me to figure it out?
You have two parameters but you are not using them in your function, since it's not clear which parameter should be used for the file path and which for the word you're searching for in the file, I have changed the parameter names for something more explanatory.
Also note, the result of below expression will be either an array of strings, a single string or $null:
$path = ... | Where-Object {$_ -like '*name*'}
Hence, your if condition if ($path -eq $true) can never be met unless $path has assigned the literal string True. If, however, you change the order of the condition to $true -eq $path, then the condition can be met and will be $true as long as $path is not $null / empty string.
$content = 'something'
$content -eq $true # => False
$true -eq $content # => True
$content = 'True'
$content -eq $true # => True
$true -eq $content # => True
From equality operators:
The equality operator can compare objects of different types. It is important to understand that the value is on the right-hand side of the comparison can be converted to the type of the left-hand side value for comparison.
Function Empdetails {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory=$true)]$FilePath,
[Parameter(Mandatory=$true)]$WordToSearch
)
$content = Get-Content $FilePath | Where-Object {$_ -like "*$wordToSearch*"}
if ($content) {
# if `$content` is populated, use return to end the function here
return Write-Host "Found"
}
Write-Host "Not Found"
}
Empdetails -FilePath ./path/to/file.ext -WordToSearch somekeyword

Powershell overwriting file contents with match instead of editing single line

I have a text file that contains a string I want to modify.
Example text file contents:
abc=1
def=2
ghi=3
If I run this code:
$file = "c:\test.txt"
$MinX = 100
$MinY = 100
$a = (Get-Content $file) | %{
if($_ -match "def=(\d*)"){
if($Matches[1] -gt $MinX){$_ -replace "$($Matches[1])","$($MinX)" }
}
}
$a
The result is:
def=100
If I omit the greater-than check like so:
$a = (Get-Content $file) | %{
if($_ -match "def=(\d*)"){
$_ -replace "$($Matches[1])","$($MinX)"
}
}
$a
The result is correct:
abc=1
def=100
ghi=3
I don't understand how a simple integer comparison before doing the replace could screw things up so badly, can anyone advise what I'm missing?
The comparison operator -gt will never get you a value of $true because you need to
cast the $matches[1] string value to int first so it compares two integer numbers
2 is never greater than 100.. Change the operator to -lt instead.
Your code outputs only one line, because you forgot to also output unchanged lines that do not match the regex
$file = 'c:\test.txt'
$MinX = 100
$MinY = 100
$a = (Get-Content $file) | ForEach-Object {
if ($_ -match '^def=(\d+)'){
if([int]$matches[1] -lt $MinX){ $_ -replace $matches[1],$MinX }
}
else {
$_
}
}
$a
Or use switch (is also faster than using Get-Content):
$file = 'c:\test.txt'
$MinX = 100
$MinY = 100
$a = switch -Regex -File $file {
'^def=(\d+)' {
if([int]$matches[1] -lt $MinX){ $_ -replace $matches[1],$MinX }
}
default { $_ }
}
$a
Output:
abc=1
def=100
ghi=3
That's because the expression ($Matches[1] -gt $MinX) is a string comparison. In Powershell, the left-hand side of a comparison dictates the comparison type and since that is of type [string], Powershell has to cast/convert the right-hand side of the expression to [string] also. You expression, therefore, is evaluated as ([string]$Matches[1] -gt [string]$MinX).

Multiple Variable Conditions for If Statement in PowerShell

Thanks for the help in this, I think i have over complicated the below but the logic just isn't responding how my mind is telling it too.
Logic in Question:
$a = "One"
$b = "Two"
$c = "Three"
$d = "Four"
If( {$a -and $b} -ne {$c and $d} ) {
Write-Host "Values are Different"
} Else {
Write-Host "values are the same"
}
I want the If statement to run when $a and $b are different to $c and $d, If the are the same see below, I want it to output that the values are the same
$a = "One"
$b = "One"
$c = "One"
$d = "One"
Thanks in advance!
You can use Compare-Object to compare the value pairs as arrays:
if (Compare-Object $a, $b $c, $d -SyncWindow 0) {
'different'
} else {
'same'
}
Note that this is convenient, but relatively slow, which may matter in a loop with many iterations.
The Compare-Object cmdlet compares two arrays and by default returns information about their differences.
-SyncWindow 0 compares only directly corresponding array elements; in other words: $a must equal $c, and $b must equal $d; without -SyncWindow, the array elements would be compared in any order so that 1, 2 would be considered equal to 2, 1 for instance.
Using the Compare-Object call's result as a conditional implicitly coerces the result to a Boolean, and any nonempty result - indicating the presence of at least 1 difference - will evaluate to $True.
As for what you tried:
Use of { ... } in your conditional is not appropriate.
Expressions enclosed in { ... } are script blocks - pieces of code you can execute later, such as with & or .
Even if you used (...) instead to clarify operator precedence (-ne has higher precedence than -and), your conditional wouldn't work as expected, however:
($a -and $b) -ne ($c -and $d) treats all variables as Booleans; in effect, given PowerShell's implicit to-Boolean conversion, you're comparing whether one value pair has at least one empty string to whether the other doesn't.
In addition to the answer from mklement0 and avoiding the rather slow Compare-Object cmdlet:
In what you tried, you will need to compare one specific value with each of the rest of the vales:
($a -eq $b) -and ($a -eq $c) -and ($a -eq $d)
Because the Comparison Operators (-eq) take a higher precedence than the Logical Operators (-and), you can leave the brackets and simplify it to:
$a -eq $b -and $a -eq $c -and $a -eq $d
To make this code DRY and easily expandable for even more values:
if ($a, $b, $c | Where {$_ -ne $d}) {
'different'
} else {
'same'
}
Just remove these {} brackets from the if statement
$a = "One"
$b = "One"
$c = "One"
$d = "One"
If($a -and $b -ne $c -and $d) {
Write-Host "Values are Different"
} Else {
Write-Host "values are the same"
}

I want to check if an element exist in an array

I want to check if a element exist in an array.
$data = "100400296 676100 582"
$i = "18320-my-turn-582"
if ($data -like $i) { Write-Host "Exist" }
else { Write-Host "Didn't exist" }
This example doesn't work like I want it. $i contains 582, so I want it to be Exist in result.
Your string "18320-my-turn-582" doesn't exist in $data, even though both strings contain the substring 582.
PowerShell treats your strings as a whole, and 18320-my-turn-582 is not present in 100400296 676100 582. To work around this you can:
Use Regex:
$i -match '\d+$'
$data -match $Matches[0]
Split the $i at hyphens so you will have:
$i = $i -split '-'
# turns $i into a array with the elements:
# 18320
# my
# turn
# 582
$data -match $i[-1]
# Output: 100400296 676100 582
Check out Get-Help about_Comparison_Operators to understand the differences between -Contains, -Match and -Like operators.