I have this issue where I must replace the string “121212” in all text files with the name of it’s parent folder (e.g. if the parent folder is named “123456” than the string “121212” should be replaced with “123456”)
I thought I figured out how to do this with the following commands:
PS E:\testenvironment> $parent=get-childitem -recurse | where {$_.FullName -match "[testenvironment]\\\d{6}$"} | foreach {$_.Name}
PS E:\testenvironment> $parent
123456
456789
654321
987654
PS E:\testenvironment> $files=get-childitem -recurse | where {$_.FullName -match "\\\d{6,6}\\AS400\\test3.txt$"} | foreach {$_.FullName}
PS E:\testenvironment> $files
E:\testenvironment\123456\AS400\test3.txt
E:\testenvironment\456789\as400\test3.txt
E:\testenvironment\654321\AS400\test3.txt
E:\testenvironment\987654\AS400\test3.txt
PS E:\testenvironment> foreach ($file in ($files)) {Get-Content "$file" | foreach-Object {$_ -replace "121212", "($name in ($parent))"} | set-content "$file"}
But I get this message :
Set-Content : The process cannot access the file 'E:\testenvironment\123456\AS400\test3.txt' **because it is being used by another process**.
At line:1 char:127
+ foreach ($file in ($files)) {Get-Content "$file" | foreach-Object {$_ -replace "121212", "($name in ($parent))"} | set-content <<<< "$file"}
+ CategoryInfo : NotSpecified: (:) [Set-Content], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand
(… i receive this for every test3.txt file ofcourse …)
I cannot figure out how to get the “current memory” into a new variable so, that the file (that would currently be in the memory) can be overwritten with the new data.
Provided all of your text files are in the directory structure you’ve posted, the following will get the job done:
Note that to ‘move’ to the next file / directory in memory, the enumeration of those items must be inside of the foreach statement whereas you were enumerating them outside.
Hope that helps.