简体   繁体   中英

Find all computers with specific text file

Trying to get this powershell script to check for a specific entry in a file on all PC's in my domain and the ones with the designated OLD server name write out to a file then run a replace on only the computers with the found value. I can get it by doing this to every PC as i know that will only apply to the ones with matching data however i have to run a stop service then a start service on each PC where i make the change and i don't want to stop/start the service on every PC in the domain. I've gotten as far as getting all PC's outputted to a file but not sure how to combine that into the IF Statement.

$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

You could check if the file on the computer has any lines that match the given word first. Then only process the file if a line is found ie something like this could be run on all computers:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM