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

会有一股神秘感。 提交于 2019-12-13 04:35:27

问题


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"

}

回答1:


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"
    }
}



回答2:


Am i able to use a select-string statement with a boolean outcome (-quiet switch) within an if statement

Yes. From the documentation:

-Quiet

Returns a Boolean value (true or false), instead of a MatchInfo object. The value is "true" if the pattern is found; otherwise, the value is "false".

Source

Are you having an issue with your current script? What prompted this question to begin with?



来源:https://stackoverflow.com/questions/18917754/in-powershell-can-i-use-the-select-string-quiet-switch-within-a-foreach-stateme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!