【问题标题】:Test-Path with variable foldername具有变量文件夹名称的测试路径
【发布时间】:2018-06-26 01:49:22
【问题描述】:

我想根据变量检查一个文件夹是否存在:

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

每次我运行脚本时,它都会丢弃自定义错误消息“无文件夹:/”,即使它存在。

如果我尝试

$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\temp\20180624:String) [Test-Path], NotSupportedException + FullyQualifiedErrorId:ItemExistsNotSupportedError,Microsoft.PowerShell.Commands.TestPathCommand 错误。

【问题讨论】:

  • 您的代码对我来说很好用。您确定文件夹的完整路径正确并且您可以访问它吗?
  • 是的,路径是正确的,我想知道第一个代码是如何为你工作的
  • 仍然有效。我将您的代码完全复制到 PS1 文件中,然后创建了一个适当的文件夹。当文件夹在那里时我没有输出,当我删除它时会弹出一个弹出窗口,这似乎是预期的行为。可能是权限、PSVersions、主机环境等问题。

标签: powershell powershell-2.0 powershell-3.0


【解决方案1】:

在 Ansgar 发表评论后编辑

以下作品

if (!(Test-Path $path))  

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

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

【讨论】:

  • 除了PowerShell auto-casts other types to boolean(如果需要)之外,使用带有布尔值的否定(!-not)非​​常好。或者更确切地说,这不仅仅是好的,这些运算符是为布尔表达式制作的。做$false -eq EXPRESSION 只会混淆事物。
猜你喜欢
  • 2019-03-30
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
相关资源
最近更新 更多