Home > Blockchain >  Powershell: Replace line that starts with string in text file by string and filename
Powershell: Replace line that starts with string in text file by string and filename

Time:06-27

I want to replace a line in a text file that starts with the value STRING: . I want to replace this line for each text file with STRING: followed by the filename without extension.

$src = "C:\Input"
Get-ChildItem $src -recurse -include *.mi | 
 Select -expand fullname |
  ForEach-Object {
            (Get-Content $_) -replace "STRING: . ","STRING: $($_.BaseName)" |
             Set-Content $_
            }

The script I have doesn't add the filename, it only replaces the line with STRING:

STRING: text to be replaced

changes into

STRING: 

while it should be

STRING: filename

How can I include the filename in the replacement action?

CodePudding user response:

Simply remove the Select -expand fullname command so you have the full FileInfo object, which is output of Get-ChildItem, available through $_ within the ForEach-Object script block:

$src = "C:\Input"
Get-ChildItem $src -file -recurse -include *.mi | 
    ForEach-Object {
        (Get-Content $_.FullName) -replace "STRING: . ","STRING: $($_.BaseName)" |
            Set-Content $_.FullName
    }

I've also added -file switch to Get-ChildItem to be explicit about what we want it to return. There could be folders named like *.mi, which might not be an issue in your case, but in general using -file is safer.

  • Related