TheDOSandDONTS
TheDOSandDONTS

Reputation: 51

Powershell - Append file name, find & replace, output to directory

I have a few automated tasks that I would like to to a directory of txt files on a daily basis. This includes:

1.Append the file name to the first row of the txt file

2.Replace the tab delimited content with semi-colons (find & replace)

3.Save the files to a sub-directory

The following code works to do the find & replace, but I am not able to save the output to a different directory, it instead overwrites the original file. Is there a different command that will allow me to save the output to a different directory?

(Get-Content "C:\Input\*.txt") -replace "`t", ";" | Set-Content "C:\Input\*.txt"

I currently have a BAT that does item 1 (append file name), but if that can be wrapped into the Powershell script I think it would be a cleaner way of doing things. Any help appreciated!

Upvotes: 0

Views: 1362

Answers (2)

TheDOSandDONTS
TheDOSandDONTS

Reputation: 51

Slight modification to the answer from Vivek which seems to be working.

Get-ChildItem "C:\Input\*.txt" | where {$_.Name -match ".txt"} | % {((Get-Content $_) -replace "`t", ";") | Set-Content "C:\Input\Upload\$($_.Name)"}

Upvotes: 1

Vivek Kumar Singh
Vivek Kumar Singh

Reputation: 3350

Not tested but you can try this -

Get-ChildItem "C:\Input\" | where {$_.Name -match ".txt"} | % {((Get-Content $_) -replace "`t", ";") | Set-Content "DifferentDirectoryPath\$($_.Name)"}

If your Input folder has sub-folders which you want to iterate then you can use this -

Get-ChildItem "C:\Input\" -Recurse -Include "*.txt" | % {((Get-Content $_) -replace "`t", ";") | Set-Content "DifferentDirectoryPath\$($_.Name)"}

Upvotes: 0

Related Questions