查找具有特定文本文件的所有计算机

Find all computers with specific text file

尝试获取此 powershell 脚本以检查我域中所有 PC 上的文件中的特定条目以及具有指定旧服务器名称的那些写入文件然后 运行 仅替换具有找到的值的计算机。我可以通过对每台 PC 执行此操作来获得它,因为我知道这将仅适用于具有匹配数据的那些但是我必须 运行 停止服务然后在我进行更改的每台 PC 上启动服务并且我不' 想要 stop/start 域中每台 PC 上的服务。我已经将所有 PC 输出到一个文件,但不确定如何将其合并到 IF 语句中。

$path = "C:\myfile.txt"
$find = "OldServerName"
$replace = "NewServerName"
$adcomputers = "C:\computers.txt"
$changes = "C:\changes.txt"

Get-ADComputer -Filter * | Select -Expand Name | Out-File -FilePath .\computers.txt

#For only computers that need the change
Stop-Service -name myservice
(get-content $path) | foreach-object {$_ -replace $find , $replace} | out-file $path
Start-Service -name myservice

您可以检查计算机上的文件是否有任何行首先匹配给定的单词。然后仅在找到一行时才处理该文件,即在所有计算机上都可能是 运行:

# Check if the computer needs the change - Find any line with the $find word
$LinesMatched = $null
$LinesMatched = Get-Content $path | Where { $_ -match $find }

# If there is one or more lines in the file that needs to be changed
If($LinesMatched -ne $null) {

    # Stop service and replace words in file.
    Stop-Service -name myservice
    (Get-Content $path) -replace $find , $replace | Out-File $path
    Start-Service -name myservice 
}