user982201
user982201

Reputation: 71

Powershell script to copy and rename files in a loop

I have a number of files with extension .psa in my Prevalidation folder and I want to:

  1. copy them one by one into my working folder
  2. rename the .psa file to psaload.csv
  3. run a set of commands against the file to load it to my db
  4. and then delete the csv file from my working folder.

This will be repeated for all the .psa files I have on my source folder.

So, the question is how do I execute the set of commands in a loop over as many .psa files as present.

Here's my piece of code testing for only one file in my Prevalidation folder -

Copy-Item  C:\Downloads\PreValidation\*.psa C:\Downloads\Validation\WIP
Rename-Item 'C:\Downloads\Validation\WIP\abc 1234.psa' 'psaload1.csv'

Get-Content C:\Downloads\Validation\WIP\psaload1.csv | ForEach-Object { $_.replace("\,"," ") } | Set-Content C:\Downloads\Validation\WIP\psaload.csv

Remove-Item C:\Downloads\Validation\WIP\psaload1.csv

<run the psaload.csv to load to my db>

This is what I intend to do -

Consider multiple .psa files in my C:\Downloads\Prevalidation folder.

For each C:\Downloads\PreValidation\*.psa

BEGIN LOOP

Copy-Item  C:\Downloads\PreValidation\aaaa.psa C:\Downloads\Validation\WIP\aaaa.psa
Rename-Item 'C:\Downloads\Validation\WIP\aaaa.psa' 'psaload1.csv'

Get-Content C:\Downloads\Validation\WIP\psaload1.csv | ForEach-Object { $_.replace("\,"," ") } | Set-Content C:\Downloads\Validation\WIP\psaload.csv

Remove-Item C:\Downloads\Validation\WIP\psaload1.csv


END LOOP

I am looking for the syntax to run these set of commands for each files one by one as present in my /prevalidation folder.

Upvotes: 3

Views: 27960

Answers (3)

Joey
Joey

Reputation: 354426

Since all the other answers were quite horrible code and not very idiomatic PowerShell, here is my take (though untested):

# Get all .psa files
Get-ChildItem C:\Downloads\PreValidation\*.psa |
   ForEach-Object {
      # Load the file's contents, replace commas with spaces
      (Get-Content $_) -replace ',', ' ' |
         # and write it to the correct folder and file name
         Out-File C:\Downloads\WIP\psaload.csv

      # I guess you'd run whatever you're doing against the file here,
      # not after the loop

      Remove-Item C:\Downloads\WIP\psaload.csv
   }

Upvotes: 5

CB.
CB.

Reputation: 60910

Try this:

$a = Get-Item .\*.psa

foreach($file in $a)
{
   Copy-Item $file.FullName "C:\Downloads\Validation\WIP\$($file.Name.replace(".psa",".psload.csv)";

remove-item $file

}

Upvotes: 0

MrKWatkins
MrKWatkins

Reputation: 2658

You can use foreach with Get-Item to do the loop. Get-Item will return a FileInfo object that you can use to get the file name (and other info) from. So you could do something like:

foreach($file in (Get-Item .\*.psa))
{
   Copy-Item $file.FullName "C:\Downloads\Validation\WIP\$($file.Name)";
}

etc.

Upvotes: 0

Related Questions