In Powershell can i use the select-string -quiet switch within a foreach statement

Mach1 picture Mach1 · Sep 20, 2013 · Viewed 9.3k times · Source

i am trying to write a script to check if a string is within a file, if it is then carry on and check the next one and continue until all are checked, if it finds one that is not present then the script will terminate. Am i able to use a select-string statement with a boolean outcome (-quiet switch) within an if statement. The pinglist.txt file contains a list of servers and the other _pinglist.ini contains a large list of servers.I am new to this so please excuse my poor scripting. Thanks

$Original_File = 'C:\Jobs\Powershell\Pinger\Other_PingList.ini'

$PingList= 'C:\Jobs\Powershell\pinglist.txt'

#

Foreach ($item in $pingList)

{If (Select-String $Original_File -pattern $item -quiet) {

Write-Host "Servers Present In File - Carrying on"

}}
Else {

   Write-Host "Servers Not Present In File - Terminating"

}

Answer

CB. picture CB. · Sep 20, 2013

give this a try

$Original_File = gc 'C:\Jobs\Powershell\Pinger\Other_PingList.ini'
$PingList= gc 'C:\Jobs\Powershell\pinglist.txt'    

Foreach ($item in $pingList)
{
    If ($Original_File -match $item ) 
    {
        Write-Host "Servers $item Present In File - Carrying on"
    }
    Else
    {
        Write-Host "Servers $item Not Present In File - Terminating"
    }
}