我在Windows XP上使用Powershell,我正在尝试编写一个命令:
1. read all .bat,.cfg, and .config files
2. replace a string (it's actually the path...these files were all moved)
3. overwrite the existing files with the new one (same name, same location, etc.)
我不是Powershell的用户,但我已经成功地将以下内容零碎:
gci -r -include "*.bat","*.config","*.cfg"
| gc
| foreach { $_ -replace "D:","C:\path" }
| sc ??.FullName
我很确定我已经处理了#1和#2,但是我很难搞清楚#3(将文件名传递给sc中可以引用的变量)。有什么想法吗?另外,如果您需要任何其他信息,请与我们联系。
修改
我设法找到答案(见下文),但是有更好的方法吗?
答案 0 :(得分:10)
尝试:
gci -r -include "*.bat","*.config","*.cfg" |
foreach-object { $a = $_.fullname; ( get-content $a ) |
foreach-object { $_ -replace "D:","C:\path" } |
set-content $a }
答案 1 :(得分:0)
我认识到我需要一个额外的变量。一种方法是将for循环集成到命令的外部。我用过:
foreach ($f in gci -r -include "*.bat")
{ (gc $f.fullname) |
foreach { $_ -replace "D:","C:\path" } |
sc $f.fullname
}
答案 2 :(得分:0)
如果要在所有文件上使用以上代码,请使用此代码,请注意第一行:
gci -r *.* |
foreach-object { $a = $_.fullname; ( get-content $a ) |
foreach-object { $_ -replace "master81","master" } |
set-content $a }
如果遗漏了*.*
,则可能会因为尝试编辑文件夹而出错。
[获取内容],UnauthorizedAccessException