Powershell: Recursively Replace String in Select S

2019-04-07 05:14发布

I'm using Powershell on Windows XP and am trying to write a command that will:

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.)

I am not a Powershell user, but I have managed to piecemeal the following together:

gci -r -include "*.bat","*.config","*.cfg" 
    | gc 
    | foreach { $_ -replace "D:","C:\path" } 
    | sc ??.FullName

I'm fairly certain that I've taken care of #1 and #2, but am having trouble figuring out #3 (passing the filename to variable that can be referenced in sc). Any thoughts? Also, let me know if you need any additional information.

EDIT:

I managed to work out an answer (see below), but is there a better way to do this?

2条回答
Rolldiameter
2楼-- · 2019-04-07 05:57

I recognized that I needed an extra variable. One way to do this is by integrating a for-loop into the outer portion of the command. I used:

foreach ($f in gci -r -include "*.bat") 
    { (gc $f.fullname) |
       foreach { $_ -replace "D:","C:\path" }  |
       sc $f.fullname 
    }
查看更多
做自己的国王
3楼-- · 2019-04-07 06:10

try:

gci -r -include "*.bat","*.config","*.cfg" |
 foreach-object { $a = $_.fullname; ( get-content $a ) |
 foreach-object { $_ -replace "D:","C:\path" }  | 
set-content $a }
查看更多
登录 后发表回答