我正在嘗試用 Powershell 替換多臺 PC 上的 test.ini 檔案中的一行。但是我需要用不同的內容替換 test.ini 檔案中的這一行。例如:
- PC st1:在 test.ini 檔案第 10 行我有“hello”,我需要用“hi”替換它
- PC st2:在 test.ini 檔案第 10 行中,我有“hello”,我需要將其替換為“bye”
我創建了一個腳本,但不明白如何在多臺 PC 上更改具有不同內容的同一行(
$devices = Get-Content "C:\script\device.txt"
foreach ($computer in $devices) {
Invoke-Command -ComputerName $computer -scriptblock {
((Get-Content -path C:\test\test.ini -Raw) -replace 'hello','world') | Set-Content -Path C:\test\test.ini
Get-Content -path C:\test\test.ini | Select -Index 10 }
}
如果我能做到,請幫忙。
uj5u.com熱心網友回復:
好的,這就是我的意思。
而不是只包含計算機名稱的文本檔案,而是像user2670623這樣的 CSV 檔案已經注釋了
ComputerName,SearchWord,Replacement
C2712,hello,hi
C1278,hello,bye
C2452,hello,again
現在,您將計算機名稱、搜索詞和該特定計算機的替換功能合而為一,然后您可以執行以下操作:
$devices = Import-Csv "C:\script\device.csv"
foreach ($computer in $devices) {
Invoke-Command -ComputerName $computer.ComputerName -ScriptBlock {
param(
[string]$findThis,
[string]$replaceWith
)
# -replace uses regex, so the $findThis string needs to be escaped because it may or may not
# contain characters that have special meaning in Regular Expressions.
(Get-Content -Path 'C:\test\test.ini' -Raw) -replace [regex]::Escape($findThis), $replaceWith | Set-Content -Path 'C:\test\test.ini'
} -ArgumentList $computer.SearchWord $computer.Replacement
}
如果由于某種原因無法創建 CSV 檔案,那么您就會陷入像這樣乏味的代碼中
$devices = Get-Content "C:\script\device.txt"
foreach ($computer in $devices) {
# for each computer, define what is to be replaced by what
switch ($computer) {
'C2712' { $find = 'hello'; $replace = 'hi' }
'C1278' { $find = 'hello'; $replace = 'bye' }
'C2452' { $find = 'hello'; $replace = 'again' }
# etcetera etcetera..
}
Invoke-Command -ComputerName $computer -ScriptBlock {
# -replace uses regex, so the $findThis string needs to be escaped because it may or may not
# contain characters that have special meaning in Regular Expressions.
(Get-Content -Path 'C:\test\test.ini' -Raw) -replace [regex]::Escape($using:find), $using:replace | Set-Content -Path 'C:\test\test.ini'
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331902.html
