Home > OS >  PowerShell - Exclude text on Select-String
PowerShell - Exclude text on Select-String

Time:02-18

I'm creating a PowerShell script to list down all the AV installed on a machine. I wanted to exclude the Windows Defender on the "If" statement when doing the checks. Below is my script:

   default
       {
       $result1 = 'There are {0} AV products installed on this system' -f $AVList.Count
       $result2 = 'DisplayNames = {0}' -f ($AVList.displayName -join ', ')
       if (Select-String -Path $workingdirectory\AVList.txt -Pattern $AVList.displayName -Exclude 'Windows Defender' -SimpleMatch -Quiet){
       $writeTxt4 = ("$(Get-Date) - [INFO]",'There are {0} AV products installed on this system.' -f $AVList.Count)
       $writeTxt5 = ("$(Get-Date) - [INFO]",'Anti-Virus Names = {0}' -f ($AVList.displayName -join ', '))
       Write-Output $writeTxt4 $writeTxt5
       Add-Content -path $report $writeTxt4
       Add-Content -path $report $writeTxt5
       }else{
       $writeTxt4 = ("$(Get-Date) - [INFO]",'There are {0} AV products installed on this system. Smile.' -f $AVList.Count)
       $writeTxt5 = ("$(Get-Date) - [INFO]",'Anti-Virus Names = {0}' -f ($AVList.displayName -join ', '))
       Write-Output $writeTxt4 $writeTxt5
         Add-Content -path $report $writeTxt4
       Add-Content -path $report $writeTxt5
       }

I tried to exclude it but still unable to make it work. Thank you so much for your help.

CodePudding user response:

From the reference of Select-String, parameter -Exclude:

Exclude the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt. Wildcards are permitted.

So this is not what we need here.

As noted in the comments, you should filter $AVList instead:

# Get all AV's, excluding "Windows Defender"
$filteredAvList = @($AVList.displayName) -notlike '*Windows Defender*'

if (Select-String -Path $workingdirectory\AVList.txt -Pattern $filteredAvList -SimpleMatch -Quiet){
    # TODO: Replace $avList by $filteredAvList 
}

When a comparison operator like -notlike is applied to a collection, it effectively filters the collection, returning only the elements that match the condition. To make sure that the operator is always applied to an array, enclose the LHS operand with the array sub-expression operator @(). Otherwise you would get a boolean result when the LHS is a single object.

  • Related