11

我在 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 中引用的变量)。有什么想法吗?另外,如果您需要任何其他信息,请告诉我。

编辑:

我设法找到了答案(见下文),但有更好的方法吗?

4

3 回答 3

13

尝试:

gci -r -include "*.bat","*.config","*.cfg" |
 foreach-object { $a = $_.fullname; ( get-content $a ) |
 foreach-object { $_ -replace "D:","C:\path" }  | 
set-content $a }
于 2012-07-06T20:38:10.533 回答
3

如果您想在所有文件上使用上述代码,请使用此代码,请注意第一行:

gci -r *.* |
foreach-object { $a = $_.fullname; ( get-content $a ) |
foreach-object { $_ -replace "master81","master" }  | 
set-content $a }

如果您遗漏,*.*您可能会收到错误,因为您正在尝试编辑文件夹。

[获取内容],未授权访问异常

于 2019-07-23T03:00:37.043 回答
0

我意识到我需要一个额外的变量。一种方法是将 for 循环集成到命令的外部。我用了:

foreach ($f in gci -r -include "*.bat") 
    { (gc $f.fullname) |
       foreach { $_ -replace "D:","C:\path" }  |
       sc $f.fullname 
    }
于 2012-07-06T20:37:27.747 回答