Reputation: 11
I am trying to find a string in the hosts files of computers in a text file. I want to check each machine in the text file for the change in the hosts file.
For security purposes, I cannot put the actual string I am searching for. I am very new to PowerShell, and I tried to do this in CMD, but I could not get the output I wanted.
$sys = Get-Content .\Systems.txt
$Loc = "\\$sys\c$\Windows\System32\Drivers\etc\hosts"
$SearchStr = "string"
$sel = Select-String -pattern $SearchStr -path $Loc
ForEach ($System in $sys) {
If ($sel -eq $null)
{
write-host $sys NotFound
}
Else
{
write-host $sys Found
}
}
Upvotes: 0
Views: 2388
Reputation: 36297
You weren't too far off, you just needed to re-think your ForEach loop a little. Move your $Loc =
line within the loop so that it updates for each system, then skip the $sel =
line and just put that in your If
check and you're all set:
$sys = Get-Content .\Systems.txt
$SearchStr = "string"
ForEach ($System in $sys) {
$Loc = "\\$system\c`$\Windows\System32\Drivers\etc\hosts"
If (Select-String -pattern $SearchStr -path $Loc -Quiet)
{
write-host "$system Found"
}
Else
{
write-host "$system Not Found"
}
}
I also escaped the dollar sign in the path for c$
. I don't think it's needed in this case, but it's good practice in general when using dollar signs that you want to actually be used as such in strings like that.
Upvotes: 1