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

Powershell 查找具有特定文本文件的所有计算机,powershell,text-parsing,Powershell,Text Parsing,尝试让此powershell脚本检查“我的域”中所有PC上的文件中的特定条目,以及具有指定旧服务器名称的文件写入文件,然后仅在具有找到的值的计算机上运行替换。我可以通过对每台PC执行此操作来获得它,因为我知道这只适用于具有匹配数据的PC,但是我必须在每台PC上运行停止服务,然后再运行启动服务,在那里我进行更改,我不想在域中的每台PC上停止/启动服务。我已经将所有PC输出到一个文件,但不确定如何将其合并到IF语句中 $path = "C:\myfile.txt" $find = "OldServe

尝试让此powershell脚本检查“我的域”中所有PC上的文件中的特定条目,以及具有指定旧服务器名称的文件写入文件,然后仅在具有找到的值的计算机上运行替换。我可以通过对每台PC执行此操作来获得它,因为我知道这只适用于具有匹配数据的PC,但是我必须在每台PC上运行停止服务,然后再运行启动服务,在那里我进行更改,我不想在域中的每台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 
} 

我不明白你想达到什么目的。当您在任何地方都不使用旧名称或新名称时,替换文本文件中的服务器名有什么用途?为什么要将所有计算机名从AD导出到完全不同的文本文件?为什么您需要在更换前停止某项服务(哪项服务?),然后再重新启动?你想做什么“改变”?请退后一步,描述您试图解决的实际问题,而不是您认为的解决方案。