PSrookie
PSrookie

Reputation: 17

Test-Path with variable foldername

I want to check whether a folder exists based on variables:

$folderdate = (Get-Date -Format "yyyyMMdd")
$foldername = "C:\Scripts\temp\$folderdate"

$path = $foldername

if (!(Test-Path $path)) {
    $wshell = New-Object -ComObject WScript.Shell
    $wshell.Popup("No folder :/ ")
    exit
}

Every time I run the script, it drops the custom error message "No folder :/ " even if it's there.

If I try

$CheckFolder = Test-Path "C:\Scripts\temp\Folder"

if ($CheckFolder) {
    continue
} else {
    $wshell = New-Object -ComObject WScript.Shell
    $wshell.Popup("No folder :/ ")
    exit
}

it works properly. I also tried without $ and the script has the same behavior. I tried $path = "C:\Scripts\temp\$foldername" but that drops a

+ CategoryInfo          : InvalidOperation: (C:\Scripts\temp\C:\Scripts\temp\20180624:String) [Test-Path], NotSupportedException
+ FullyQualifiedErrorId : ItemExistsNotSupportedError,Microsoft.PowerShell.Commands.TestPathCommand error.

Upvotes: 1

Views: 1344

Answers (1)

Micky Balladelli
Micky Balladelli

Reputation: 9991

Edited after comment from Ansgar

The following works

if (!(Test-Path $path))  

Also in the second test you tried, $foldername already contained a path, which means you concatenated two paths names. The exception is reporting it:

C:\Scripts\temp\C:\Scripts\temp\20180624

Upvotes: 1

Related Questions