How Do You Troubleshoot a PowerShell Error “CreateFromDirectory … The Path Is Not of a Legal Form”?

Problem scenario
You want a PowerShell script to place files from a folder into one zip file.

When using PowerShell version 3, your script throws this error:

Exception calling "CreateFromDirectory" with "2" argument(s): "The path is not of a legal form."
At line...
     CategoryInfo                  : NotSpecified: (:) [], MethodInvocationException
     FullyQualifiedErrorId       : ArgumentException 
The offending line of code looks like this:

[System.IO.Compression.ZipFile]::CreateFromDirectory($sourcefolder, $destinationzip)

How do you troubleshoot or fix this problem?

To resolve the problem, rewrite the code to utilize the Reflection.Assembly.  Here is a complete (standalone), working script that works by itself assuming you have .Net Framework 4.5 or higher installed on your Windows machine:

$sourceFolderName = "C:\Users\jdoe\Documents\folderwithfiles\"
$destinationZipFileName = "C:\Users\jdoe\Documents\destination\" 
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceFolderName, $destinationZipFileName)

# Just change the $sourceFolderName and $destinationZipFileName as you desire.
# The above script will place all the files in $sourceFolderName into $destinationZipFileName.

Leave a comment

Your email address will not be published. Required fields are marked *