Home > Blockchain >  Power Shell: Need to put the file specific name in the file content
Power Shell: Need to put the file specific name in the file content

Time:12-24

I have a file test001.txt where I need to replace one word with the file name. For example:

File name: test001.txt contains "Send gift to CUSTOMER"

I need to replace CUSTOMER with the name of the file "test001" but to be automatically made. It means that I have multiple files in a folder, I want to copy them in another folder, and when I copy them I want all the files to have that word replace the name of its file name

test001, test002, test003 ..etc, so instead of CUSTOMER in every file, there will be: test001, test002, test003...

I tried:

Copy-Item "C:\Location1\*" -Destination "C:\location2"  -----to copy all files 

$fileName = "C:\Location1\*"   ----to take names for all files

$currentDate = get-date -format "yyMMdd"

$automationTest = "C:\Location2\test1.DDI"  ---name of new file

$content = [System.IO.File]::ReadAllText($automationTest).Replace("CUSTOMER",$fileName)
[System.IO.File]::WriteAllText($automationTest, $content)

but it's actually replacing with "C:\Location1*", not the name of the file in that location

Any ideas? Thank u! :)

CodePudding user response:

You can use Get-ChildItem and a loop for this. BaseName is the name of the file without the extension in the code below and note that I'm using -creplace which is case sensitive ("customer" will not be replaced but "CUSTOMER" will) in case you don't need this use -replace.

$replaceWord = 'CUSTOMER'

Get-ChildItem path/to/giftfiles -Filter *.txt | ForEach-Object {
    (Get-Content $_ -Raw) -creplace $replaceWord, $_.BaseName |
    Set-Content $_.FullName
}
  • Related