我试图用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:scriptdevice.txt"
foreach ($computer in $devices) {
Invoke-Command -ComputerName $computer -scriptblock {
((Get-Content -path C:testtest.ini -Raw) -replace 'hello','world') | Set-Content -Path C:testtest.ini
Get-Content -path C:testtest.ini | Select -Index 10
}
}
如果我能做的话,请帮帮我。
好了,这就是我的意思。
与其只包含计算机名的文本文件,不如将其创建为CSV文件,如user2670623已注释
ComputerName,SearchWord,Replacement
C2712,hello,hi
C1278,hello,bye
C2452,hello,again
现在你有了计算机名称,搜索词和替换的特定计算机在一起然后你可以这样做:
$devices = Import-Csv "C:scriptdevice.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:testtest.ini' -Raw) -replace [regex]::Escape($findThis), $replaceWith | Set-Content -Path 'C:testtest.ini'
} -ArgumentList $computer.SearchWord $computer.Replacement
}
如果由于某种原因无法创建CSV文件,那么您就只能使用像
这样冗长的代码了。$devices = Get-Content "C:scriptdevice.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:testtest.ini' -Raw) -replace [regex]::Escape($using:find), $using:replace | Set-Content -Path 'C:testtest.ini'
}
}