Powershell 具有变量foldername的测试路径
我想根据变量检查文件夹是否存在:Powershell 具有变量foldername的测试路径,powershell,powershell-2.0,powershell-3.0,Powershell,Powershell 2.0,Powershell 3.0,我想根据变量检查文件夹是否存在: $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 }
$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\temp\20180624:String) [Test-Path], NotSupportedException
+ FullyQualifiedErrorId : ItemExistsNotSupportedError,Microsoft.PowerShell.Commands.TestPathCommand error.
+CategoryInfo:InvalidOperation:(C:\Scripts\temp\C:\Scripts\temp\20180624:String)[测试路径],NotSupportedException
+FullyQualifiedErrorId:ItemExistSnotSupporterRor,Microsoft.PowerShell.Commands.TestPathCommand错误。
根据Ansgar的评论进行编辑 以下作品
if (!(Test-Path $path))
同样在第二个测试中,您尝试,$foldername已经包含一个路径,这意味着您连接了两个路径名。例外情况是报告它:
C:\Scripts\temp\C:\Scripts\temp\20180624
你的代码对我来说很好。你确定文件夹的完整路径是正确的并且你有权访问它吗?是的,路径是正确的,我想知道你的第一个代码是如何工作的。我将您的代码完全复制到PS1文件中,然后创建了一个适当的文件夹。当文件夹在那里时,我没有输出,当我删除它时,会弹出一个窗口,这似乎是预期的行为。可能是权限、PSVersions、主机环境等方面的问题。除了PowerShell(如果需要)之外,使用带有布尔值的否定(
!
,-而不是
)是完全正确的。或者更确切地说,这不仅仅是好的,这些操作符是为布尔表达式设计的。执行$false-eq表达式
只会使事情变得混乱。