Powershell: Recursively Replace String in Select Sub-files of a Directory

我是研究僧i 提交于 2019-12-21 11:30:04

问题


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?


回答1:


try:

gci -r -include "*.bat","*.config","*.cfg" |
 foreach-object { $a = $_.fullname; ( get-content $a ) |
 foreach-object { $_ -replace "D:","C:\path" }  | 
set-content $a }



回答2:


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:


If you want to use the above code on ALL FILES use this code, note the top line:

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

if you leave out *.* you may get errors because you are trying to edit folders.

[Get-Content], UnauthorizedAccessException



来源:https://stackoverflow.com/questions/11368786/powershell-recursively-replace-string-in-select-sub-files-of-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!