- 1 year ago
How to replace a line in a file on multiple computers using PowerShell
To replace a line in a file on multiple computers using PowerShell, you can use PowerShell remoting. Here's a step-by-step guide:
Create a text file that contains the list of computer names or IP addresses of the remote computers, with each name or address on a new line. Save it as
computers.txt
(or any other name you prefer) in the same directory as your PowerShell script.Open PowerShell and navigate to the directory where your script and
computers.txt
file are located.Create a PowerShell script file with a name like
ReplaceLine.ps1
and open it in a text editor.In the script file, add the following code:
powershell$computers = Get-Content -Path .\computers.txt
$filePath = "C:\Path\to\your\file.txt" # Replace with the actual file path
$lineNumber = 5 # Replace with the line number you want to replace
$newLine = "This is the new line" # Replace with the new line text
foreach ($computer in $computers) {
Invoke-Command -ComputerName $computer -ScriptBlock {
param($filePath, $lineNumber, $newLine)
$content = Get-Content -Path $filePath
$content[$lineNumber - 1] = $newLine
$content | Set-Content -Path $filePath
} -ArgumentList $filePath, $lineNumber, $newLine
}
Modify the
$filePath
,$lineNumber
, and$newLine
variables in the script to match your requirements.$filePath
should be the path to the file you want to modify on the remote computers.$lineNumber
should be the line number you want to replace (e.g., if you want to replace the third line, set it to 3).$newLine
should contain the text you want to replace the line with.
Save the script file.
In the PowerShell console, run the script by executing the following command:
powershell.\ReplaceLine.ps1
The script will read the list of computers from computers.txt
and iterate over each computer. It will establish a remote PowerShell session with each computer using Invoke-Command
and replace the specified line in the specified file on each remote computer.
Note: To use PowerShell remoting, you need to have administrative privileges on the remote computers, and the WinRM (Windows Remote Management) service must be enabled on the remote computers.