I am not too familiar with Windows PowerShell (and Windows console commands in general), but I wish to write a batch file which can create sperated .zip archives from specific files in a folder, then delete all but the .zip files. So, I have a folder as "C:\myfolder\" and some files in it like: myfile0001.a myfile0001.b myfile0001.c myfile0002.a myfile0002.b myfile0002.c myfile0003.a myfile0003.b myfile0003.c ... and so on.
I want a create a .zip for every myfileXXXX.a + myfileXXXX.b + myfileXXXX.c package and name the .zips as the file names (for example myfile0001.zip would contain myfile0001.a + myfile0001.b + myfile0001.c).
I know that I can use this code to create each .zip archive one-by-one:
powershell -Command "& {Compress-Archive -Path C:\myfolder\myfile0001.* -CompressionLevel Optimal -DestinationPath C:\myfolder\myfile0001.zip}"
And this code working fine to delete all but the .zip archives
powershell -Command "& {Remove-Item C:\myfolder\*.* -Exclude *.zip}"
What I cannot solve is to create a for cycle which can loop through all myfileXXXX.* and create a myfileXXXX.zip using the XXXX as the increasing value.
In PowerShell, you could do:
Get-ChildItem -Path 'C:\myfolder' -File | Where-Object { $_.BaseName -match 'myfile\d{4}' } | Group-Object BaseName | ForEach-Object {
$target = Join-Path -Path ($_.Group[0].DirectoryName) -ChildPath ('{0}.zip' -f $_.Group[0].BaseName)
$_.Group | Compress-Archive -CompressionLevel Optimal -DestinationPath $target
$_.Group | Remove-Item -Force
}
Writing it as commandline gets a little ugly, but here you go:
powershell -Command "& {Get-ChildItem -Path 'C:\myfolder' -File | Where-Object { $_.BaseName -match 'myfile\d{4}' } | Group-Object BaseName | ForEach-Object { $target = Join-Path -Path ($_.Group[0].DirectoryName) -ChildPath ('{0}.zip' -f $_.Group[0].BaseName); $_.Group | Compress-Archive -CompressionLevel Optimal -DestinationPath $target; $_.Group | Remove-Item -Force}}"