How to compare Folder Name to a zip file name

I have created a script that looks at “older than two years” files in source location, and create a zip for files from each year. So files from 2015 would be zipped into 2015.zip, files from 2016 into 2016.zip so on and so forth. Issue I am running into is that I need to check if the file already exists, if it does than pass over that year and move onto the next year - which I am unable to figure out yet, since I have to compare the name of the folder vs name of zip file (test-path won’t work), like folder named “2015” vs zip named 2015.zip. Furthermore, I create a temporary folder for each year move the files to it then zip them back in the source location. I can provide my code hear if needed, but thanks in advance for your help.

# Exit script in case of any error $ErrorActionPreference = 'Stop' Add-Type -assembly "system.io.compression.filesystem"

$SourcePath = “C:\Users\archive”
$destination = “C:\Users\archive{0}.zip”
$logfile=“C:\Users\archive\zipfiles_folders.log”

$groups = Get-ChildItem $SourcePath -exclude *.zip |
Where-Object{ ($.LastWriteTime.Year -le [datetime]::Now.year - 2) -and ($.psIsContainer -eq $false) } |
Group-Object { “{0:yyyy}” -f $_.LastWriteTime }

if($groups -eq $null){
write-output “NO FILES TO ARCHIVE.” >> $logfile
}

Create a temporary working dir

$TmpDirPath = "C:\Test"
$TmpDirectory = New-Item -Path $TmpDirPath -ItemType Directory

ForEach ($group in $groups){
$FileNames = ($group.Name)

delete temp directorty to save space on C:\

if (test-path -path $GroupDirectory){
del $GroupDirectory -recurse -force
}

Create a new directory for the group

$GroupDirectory = New-Item -Path (Join-Path $TmpDirectory.FullName -ChildPath $group.Name) -ItemType Directory

if (test-path “$destination$FileNames.zip”){
write-output " already exists!" >> $logfile
}
else{

Move files into the new directory

$group.Group | Move-Item -Destination $GroupDirectory.FullName
}

Create the year-specific zip file

[System.IO.Compression.ZipFile]::CreateFromDirectory($GroupDirectory.FullName, ($destination -f $group.Name))
write-output “$FileNames.zip CREATED.” >> $logfile
}

Since, you have not shown the code you are trying, thus forcing us to try and read your use case and write code for you, which would be based on assumptions and thus wrong.

You can use Test-Path or Get-ChildItem to check for a folder name or part of a folder name, or just match on a substring or RegEx match.

Get-ChildItem -Path E:\Zipped | Format-Table -AutoSize

# Results

<#
    Directory: E:\Zipped


Mode          LastWriteTime Length Name   
----          ------------- ------ ----   
d-----   3/7/2019   3:36 PM        Zip2016
d-----   3/7/2019   3:32 PM        Zip2017
d-----   3/7/2019   3:32 PM        Zip2018


    Directory: E:\Zipped\Zip2016


Mode          LastWriteTime Length Name                      
----          ------------- ------ ----                      
-a----   3/7/2019   3:31 PM      0 New Text Document_2016.txt


    Directory: E:\Zipped\Zip2017


Mode          LastWriteTime Length Name                      
----          ------------- ------ ----                      
-a----   3/7/2019   3:31 PM      0 New Text Document_2017.txt


    Directory: E:\Zipped\Zip2018


Mode          LastWriteTime Length Name                      
----          ------------- ------ ----                      
-a----   3/7/2019   3:31 PM      0 New Text Document_2018.txt
#>



((Get-ChildItem -Path 'E:\Zipped' -Directory).FullName) -Match '2017|2018'

# Results

<#
E:\Zipped\Zip2017
E:\Zipped\Zip2018
#>



# Using Test-Path
'2017','2018' | %{Test-Path -Path "E:\Zipped\*$PSItem"}

# Results

<#
True
True
#>

For the zip file, you just need to add in the extension.

Thanks.

I have added script now.

I am going to assume you are using the .Net name space because you are on an OS/PS version that does have the Compress-* cmdlets as well as using .Net for datetime vs the Built-In Get-Date that’s been in PS since day 1.

Get-Command -Name '*archive*' | Format-Table -AutoSize

CommandType Name             Version Source                      
----------- ----             ------- ------                      
Function    Compress-Archive 1.0.1.0 Microsoft.PowerShell.Archive
Function    Expand-Archive   1.0.1.0 Microsoft.PowerShell.Archive

For the date, using Get-Date.

(Get-Date).Date.AddYears(-2).Year

Yeppers, it’s a bit longer in the tooth, but, you know, it’s PS. ;-}

Yet, you have a lot going on in the script, and outside of the Test-Path / compare thing, which I’ve already addressed, you should be fine. I would have approached this a bit differently for simplification.

For example changing this …

$groups = Get-ChildItem $SourcePath -exclude *.zip |
Where-Object{ 
    ($_.LastWriteTime.Year -le [datetime]::Now.year – 2) -and
    ($_.psIsContainer -eq $false) 
 }

… to this.

$groups = Get-ChildItem -File -Path $SourcePath\* -Exclude '*.zip' | 
Where-Object -Property LastWriteTime -le $((Get-Date).Date.AddYears(-2))

Yet, it’s all about choice.

I keep getting this error:

Test-Path : Cannot bind argument to parameter ‘Path’ because it is null.
At line:29 char:25

  • if (test-path -path $GroupDirectory){
  • CategoryInfo : InvalidData: (:slight_smile: [Test-Path], ParentContainsErrorRecordException
  • FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand

And it’s at this line here

if (test-path -path $GroupDirectory){
del $GroupDirectory -recurse -force
}

Can you please guide me on this as I have looked at other resources but don’t see anything useful. Note that my script is actually doing join-path to create $GroupDirctory.

Thanks!

As for …

if (test-path -path $GroupDirectory){
 del $GroupDirectory -recurse -force
 }

… You don’t have that variable populated from anything / anywhere, thus it’s null.

Just put your cursor at the top of your script and do a search for $GroupDirectory and you’ll see that the first place it lands is that if statement. What is supposed to be in that?

Thanks postanote!

It was written on my forehead but couldn’t see it until you asked this question.
Now, $GroupDirectory is temporary directory to hold data-set per year before it is zipped up to the $destination location. However, I am working with large data and want to avoid blowing up C:\ drive by deleting $GroupDirectory before moving on to the next year’s data-set for each $group(this holds all data for one year).

This is what I needed to do:

if (test-path -path $TmpDirectory){ del $TmpDirectory -recurse -force }

It turns out that PS Version2 on our client’s servers doesn’t have Compress-Archive, so I regressed and now using an in-house zipping utility which keeps throwing following error. This utility returns retval = 0 as successful completion but my powershell goes nuts and:

    dtflate : retval = 0 At line:41 char:5 + smflate -z $GroupDirectory ($destination -f $group.Name) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (retval = 0:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError

Once again, what do you suggest?
Thanks!