具有可变文件夹名称的测试路径

Test-Path with variable foldername

我想根据变量判断文件夹是否存在:

$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
}

每次我 运行 脚本时,它都会删除自定义错误消息 "No folder :/ " 即使它在那里。

如果我尝试

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

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

它工作正常。我也尝试过不使用 $ 并且脚本具有相同的行为。 我试过 $path = "C:\Scripts\temp$foldername" 但那掉落了

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

根据 Ansgar 的评论进行编辑

以下作品

if (!(Test-Path $path))  

同样在您尝试的第二个测试中,$foldername 已经包含一个路径,这意味着您连接了两个路径名称。异常正在报告它:

C:\Scripts\temp\C:\Scripts\temp180624