这可能很简单,但是我试图编写一个脚本,以便将已安装程序的目录从一台计算机移动到另一台计算机时使用。为了使此工作正常进行,我必须从旧计算机上找到旧主机名,旧IP地址和旧驱动器号的每个实例,并用新主机名,新IP地址和新驱动器号替换它们。新机器。主文件夹包含* .xml和* .config文件,这些文件需要在主文件夹以及子文件夹中进行编辑。
这是我正在使用的代码:
$oldIP = "192.168.1.2"
$newIP = "192.168.1.3"
$oldhost = "OLDHOSTNAME"
$newhost = "NEWHOSTNAME"
$oldDriveLetter = "C"
$newDriveletter = "E"
$path = "\\$newip\$newdriveletter$\Folder"
$files = get-childitem $path\* -include *.xml, *.config, -recurse
$files | %{
(gc $_) -replace $oldhost, $newhost -replace $oldip, $newip -replace "${olddriveletter}:\Folder", "${newDriveLetter}:\Folder" | set-content $_.fullname
}
当前,它仅替换主文件夹中的值,而不替换任何子文件夹中的值。知道我想念什么吗?
编辑:根据下面的建议,我在* .config之后删除了逗号,这似乎使我了解了子文件夹。但是它仍然没有用E:\ Folder
替换任何C:\ Folder实例。答案 0 :(得分:1)
这很好。将逗号放在* .config的末尾,并在$ {olddriveletter}:\ Folder的中间添加了另一个\。
$oldIP = "192.168.1.2"
$newIP = "192.168.1.3"
$oldhost = "OLDHOSTNAME"
$newhost = "NEWHOSTNAME"
$oldDriveLetter = "C"
$newDriveletter = "E"
$path = "."
$files = get-childitem $path\* -include *.xml, *.config -recurse
$files | %{
(gc $_) -replace $oldhost, $newhost -replace $oldip,
$newip -replace "${olddriveletter}:\\Folder","${newDriveLetter}:\Folder" |
set-content $_.fullname
}
试图简化一下。太糟糕了,您不能只执行“ get-childitem | get-content -replace | set-content”。
get-childitem $path\* -include *.xml, *.config -recurse |
foreach {
(get-content $_) -replace $oldhost,$newhost -replace $oldip,
$newip -replace "${olddriveletter}:\\Folder", "${newDriveLetter}:\Folder" |
set-content $_
}
答案 1 :(得分:0)
我建议:
## Q:\Test\2019\05\09\SO_56064191.ps1
$oldIP = "192.168.1.2"
$newIP = "192.168.1.3"
$oldhost = "OLDHOSTNAME"
$newhost = "NEWHOSTNAME"
$oldDriveLetter = "C"
$newDriveletter = "E"
$path = '\\{0}\{1}$\Folder' -f $newip,$newdriveletter
ForEach($File in (Get-ChildItem $path\* -Include *.xml,*.config -Recurse)){
(Get-Content $File.FullName -raw) -replace [RegEx]::Escape($oldhost),$newhost `
-replace [RegEx]::Escape($oldip),$newip `
-replace "$olddriveletter(?=:\Folder)",$newDriveLetter |
Set-Content $File.FullName -NoNewline
}