我正在尝试在文本文件中的计算机的hosts文件中找到一个字符串。我想检查文本文件中的每台机器以查找hosts文件中的更改。
出于安全考虑,我无法输入我正在搜索的实际字符串。我是PowerShell的新手,我试图在CMD中做到这一点,但我无法得到我想要的输出。
$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
}
}
答案 0 :(得分:1)
你并没有太远,你只需要重新思考你的ForEach循环。在循环中移动$Loc =
行,使其针对每个系统进行更新,然后跳过$sel =
行并将其放入If
检查中,然后全部设置完毕:
$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"
}
}
我还在c$
路径中逃过了美元符号。在这种情况下我不认为这是必要的,但是在使用美元符号时,一般都是很好的做法,你想要在这样的字符串中实际使用它。