Anthony Barker
Anthony Barker

Reputation: 21

powershell how to loop over files and zip them

First time powershell development - have to say not intuitive for a linux scripter.

need to loop over files to zip them and getting errors - anyone have some feedback on a good one liner?

gci C:\temp -r *.csv | 
Where-Object { $_.lastwritetime -lt (Get-date).AddDays(-10)} | 
ForEach-Object {'c:\temp\bin\gzip.exe' $_.FullName}

Upvotes: 2

Views: 2429

Answers (3)

jon Z
jon Z

Reputation: 16616

The following version of your script could come in handy when you can't rely on external tools:

gci C:\temp -recurse *.csv | 
Where-Object { $_.lastwritetime -lt (Get-date).AddDays(-10)} | 
ForEach-Object {
  $zip =  $_.fullname -replace "\.csv",".zip"; 
  new-item -type File $zip -force;
  ((new-object -com shell.application).namespace($zip)).copyhere($_.fullname)
}

Upvotes: 1

manojlds
manojlds

Reputation: 301137

Applications can be executed in Powershell just by giving their name / path, you don't have to enclose them in quotes as strings and then use iex or &:

c:\temp\bin\gzip.exe $_.FullName

would work for the zipping part.

Upvotes: 2

x0n
x0n

Reputation: 52420

You're missing the call (&) operator to actually execute the command in the string. If you don't do this, the string is printed out as the result of an expression evaluation (instead of as a command.)

gci C:\temp -r *.csv `
    | Where-Object { ... } `
    | ForEach-Object { & 'c:\temp\bin\gzip.exe' $_.FullName}

Incidentally, if you install the PowerShell Community Extensions (http://pscx.codeplex.com) then this becomes much simpler:

   ls c:\temp -r *.csv `
       | where { ... }
       | write-gzip

Upvotes: 4

Related Questions