agfila
agfila

Reputation: 23

Use txt file as list in PowerShell array/variable

I've got a script that searches for a string ("End program" in this case). It then goes through each file within the folder and outputs any files not containing the string.

It works perfectly when the phrase is hard coded, but I want to make it more dynamic by creating a text file to hold the string. In the future, I want to be able to add to the list of string in the text file. I can't find this online anywhere, so any help is appreciated.

Current code:

$Folder = "\\test path"
$Files = Get-ChildItem $Folder -Filter "*.log" |
         ? {$_.LastWriteTime -gt (Get-Date).AddDays(-31)} 

# String to search for within the file
$SearchTerm = "*End program*"

foreach ($File in $Files) {
    $Text = Get-Content "$Folder\$File" | select -Last 1

    if ($Text | WHERE {$Text -inotlike $SearchTerm}) {
        $Arr += $File
    }
}
if ($Arr.Count -eq 0) {
   break
}

This is a simplified version of the code displaying only the problematic area. I'd like to put "End program" and another string "End" in a text file.

The following is what the contents of the file look like:

*End program*,*Start*

Upvotes: 0

Views: 4150

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

If you want to check whether a file contains (or doesn't contain) a number of given terms you're better off using a regular expression. Read the terms from a file, escape them, and join them to an alternation:

$terms = Get-Content 'C:\path\to\terms.txt' |
         ForEach-Object { [regex]::Escape($_) }

$pattern = $terms -join '|'

Each term in the file should be in a separate line with no leading or trailing wildcard characters. Like this:

End program
Start

With that you can check if the files in a folder don't contain any of the terms like this:

Get-ChildItem $folder | Where-Object {
    -not $_.PSIsContainer -and
    (Get-Content $_.FullName | Select-Object -Last 1) -notmatch $pattern
}

If you want to check the entire files instead of just their last line change

Get-Content $_.FullName | Select-Object -Last 1

to

Get-Content $_.FullName | Out-String

Upvotes: 1

Related Questions