I am trying to print out a line in a text file if it starts with any of the string in the array.
Here is a snippet of my code:
array = "test:", "test1:"
if($currentline | Select-String $array) {
Write-Output "Currentline: $currentline"
}
My code is able to print lines in the text file if it has any of the strings in the array variable. But I only want to print lines if it starts with the string in array variable.
Sample of text file:
abcd-test: 123123
test: 1232
shouldnotprint: 1232
Output:
abcd-test: 123123
test: 1232
Expected output:
test: 1232
I have seen some questions asked on stackoverflow with the solution:
array = "test:", "test1:"
if($currentline | Select-String -Pattern "^test:") {
Write-Output "Currentline: $currentline"
}
But in my case I am using an array variable instead of a string to select the content so I am stumped at this portion because it would not work. It will just now print anything.
Update: Thanks Theo for your answer! This is my code based on Theo's answer for reference
array = "test:", "test1:"
$regex = '^({0})' -f (($array |ForEach-Object { [regex]::Escape($_) }) -join '|')
Loop here:
if($currentline -match $regex) {
Write-Output "Currentline: $currentline"
}