Nenad
Nenad

Reputation: 11

How can I pass a path in PowerShell, I am getting an error that I can't figure out

This is one of my first powershell scripts and I can't make it work. I can't pass "c:\" as a destination folder.

My script:

$sourceFolder = "C:\Temp"
$winZipExe = "C:\Program Files\WinZip\WZUNZIP.EXE"
$destinationFolder = "c:\"
$passwordCommand

# Ask the user for a password
$password = Read-Host -Prompt "Please enter the password for the .zipx files"
$passwordCommand = "-s" + $password.ToString()

Get-ChildItem -Path $sourceFolder -Filter *.zipx | ForEach-Object {
    $zipxFile = $_.FullName
    $zipxFileName = $_.BaseName
    $outputFolder = (Resolve-Path $destinationFolder) ; $destinationFolder
    New-Item -ItemType Directory -Path $outputFolder -Force
    & $winZipExe -e -d $passwordCommand $zipxFile #$outputFolder
}

My error:

c:\
New-Item : The path is not of a legal form.
At C:\Users\Nenad A. Dragic\Desktop\Unzip1.ps1:14 char:5
+     New-Item -ItemType Directory -Path $outputFolder -Force
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (C:\:String) [New-Item], ArgumentException
    + FullyQualifiedErrorId : CreateDirectoryArgumentError,Microsoft.PowerShell.Commands.NewItemCommand

I have tested with this: $outputFolder = ""

Done a lot of different arguments from Google, Stackoverflow and chatGPT, but can't make it work.

My zipx files contains a folder with the files in it and I would like it to unzip to C:\

Upvotes: 1

Views: 878

Answers (2)

mklement0
mklement0

Reputation: 437042

Nawad-sama's answer offers a potential solution - don't try to write directly to C:\ - but let me address the error cause:

The error isn't caused by a lack of permissions (though you may run into permission issues later), it is caused by an - ultimately inconsequential - bug in Windows PowerShell, which has since been fixed in PowerShell (Core) 7+

While it never makes sense to try to create a drive's root directory - if the drive is accessible, it by definition already has a root drive - the addition of the -Force switch to New-Item -ItemType Directory should return information about the existing root drive (in the form of a System.IO.DirectoryInfo instance; that is what now happens in PowerShell (Core) 7+).

Due to the bug, you get an obscure error message instead (The path is not of a legal form.)

Upvotes: 0

Nawad-sama
Nawad-sama

Reputation: 181

You probably don't have permissions to write directly to C Drive. Try changing $destinationFolder to something depper. I.e. C:\"YOUR_USERNAME".

Upvotes: 0

Related Questions