0

I have a folder with multiple files. I want to read each file and replace with whatever the user passes to the application (a parameter). After the content of the file is replaced, I want to save the file in a new folder.

This is what I have so far:

gci C:\Users\Person\Documents\Test1\*.bat -recurse | ForEach {
  (Get-Content $_ | ForEach {$_ -replace "<client_instance>", "ClientName"}) | Set-Content $_ 
}

My first question is, is this correct and secondly, how do I change "Set-Content" so that it saves the files in a different folder?

I want to use variables for the source and destination:

$sourePath
$destinationPath

I'm new to PowerShell so any help would be greatly appreciated. Thanks.

1 Answer 1

1

Yes, your code is fine. You can build your new path like this:

$files = gci C:\Users\Person\Documents\Test1\*.bat -recurse
$destinationpath = "C:\users\person\documents\test2"
ForEach ($file in $files){
    Get-Content $file.fullname | ForEach {$_ -replace "<client_instance>", "ClientName"} | set-content "$destinationpath\$($file.basename)"
}

You might have to tweak it here and there to fit your needs.

Sign up to request clarification or add additional context in comments.

5 Comments

this worked. thank you. i just had to add ".bat" for the destination file type. i can accept your answer in 3 mins.
Why is changing to Out-File required? You could just as easily do Set-Content "$destinationpath\$($file.basename)". The major point is that Get-Content $_ | ... | Set-Content $_ overwrites the source file.
I definitely don't want to replace the original file. I want to create a copy with the replaced values.
@BACON You're completely right, I've somehow taken "change set-content" literally. Edited my answer to be more concise what had to be changed.
@RJ. Right. The problem with the Set-Content $_ that you used is not Set-Content but the value passed for the -Path parameter, $_.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.