Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a command on each directory in a list using PowerShell

I've got a need to make a .zip of each directory in a list in PowerShell. I for some reason cannot figure out how to change to each directory to run a command relative to that path though.

Here is my situation:

$dir = Get-ChildItem d:\directory | ? {$_.PSIsContainer}

$dir | ForEach-Object {Set-Location $_.FullName;
Invoke-Expression "7z.exe A" +  $_.Name + ".rar " + $_.Path + "\"}

The command is ugly, but due to the way that 7Zip seems to parse text, I had to go this way. I believe the command should make a ZIP file in each directory, with the name set equal to the directory name, and include all of the files in the directory.

It seems like I'm stuck in some PowerShell hell though where I cannot even access the values of objects for some reason.

For instance, if I echo $dir, I see my list of directories. However, if I try

gci $dir[1]

PowerShell returns nothing. It's not actually enumerating the directory path contained within the variable property, but instead trying to list the items contained within that value, which would of course be empty.

What gives?! How do I do this?

like image 606
FoxDeploy Avatar asked Jul 16 '13 17:07

FoxDeploy


People also ask

How do I get a list of files in a directory and subfolders using PowerShell?

PowerShell utilizes the “Get-ChildItem” command for listing files of a directory. The “dir” in the Windows command prompt and “Get-ChildItem” in PowerShell perform the same function.

How do I list the contents of a directory in PowerShell?

On a Windows computer from PowerShell or cmd.exe, you can display a graphical view of a directory structure with the tree.com command. To get a list of directories, use the Directory parameter or the Attributes parameter with the Directory property. You can use the Recurse parameter with Directory.

What is foreach loop in PowerShell?

The foreach statement (also known as a foreach loop) is a language construct for stepping through (iterating) a series of values in a collection of items. The simplest and most typical type of collection to traverse is an array.


1 Answers

You don't need to set the location, you just just provide paths to 7z.exe. Also, 7zip does not compress to Rar, only decompress.

$dir = dir d:\directory | ?{$_.PSISContainer}

foreach ($d in $dir){
    $name = Join-Path -Path $d.FullName -ChildPath ($d.Name + ".7z")
    $path = Join-Path -Path $d.FullName -ChildPath "*"

    & "C:\Program Files\7-Zip\7z.exe" a -t7z $name $path
}
like image 99
logicaldiagram Avatar answered Oct 22 '22 00:10

logicaldiagram