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?
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With