PowerShell脚本中的测试路径

问题描述:

代码(底部)来自powershell脚本,我试图检查是否存在两个不同的目录。如果该目录存在,它应该执行remove-item以删除其下的所有文件和文件夹。PowerShell脚本中的测试路径

然而,当我运行该脚本,我得到以下输出:

如果:执行操作的目标 “删除文件” “\ server1的\ C $ \ WINDOWS \ propatches \补丁\ WindowsServer2003的-KB2621440.exe” 。

如果执行操作“删除文件”目标“\ server1 \ c $ \ windows \ propatches \ patches \ WindowsServer2003-KB2641653.exe”。

Remove-Item:指定路径\ server1 \ c $ \ winnt \ propatches \ patches中的对象不存在。 在C:\ Documents和Settings \ LogonUser的\桌面\ GetPCNames.ps1:32字符:14 +删除-项目< < < < $的ClearPath -recurse -whatif + CategoryInfo:ObjectNotFound:(\ SEARCHMGT1 \ C $ \ WINNT \ propatches \补丁:字符串)[删除-项目],IOException的 + FullyQualifiedErrorId:ItemDoesNotExist,Microsoft.PowerShell.Commands.RemoveItemCommand

好像第一测试路径被检测到所述目录中存在与删除项正确运行。

但是,第二个测试路径(它不存在)仍会尝试执行remove-item命令,因为该路径不存在而剔除。

我假设我的测试路径,如果声明必须是错误的,但我拉出我的头发试图找出我做错了什么。任何人都知道为什么这会产生错误?

foreach ($objResult in $colResults) 
{ 
$objComputer = $objResult.Properties; 

$path1 = "\\" + $objComputer.name + "\c$\windows\propatches\patches\" 
$path2 = "\\" + $objComputer.name + "\c$\winnt\propatches\patches\" 

#check to see if it is missing 
if ((Test-Path -path $path1)) 
{ 
    $clearpath = $path1 + "*" 
    Remove-Item $clearpath -recurse -whatif 
} 

#check to see if it is missing 
if ((Test-Path -path $path1)) 
{ 
    $clearpath = $path2 + "*" 
    Remove-Item $clearpath -recurse -whatif 
} 
+0

谢谢!我想我一直在盯着剧本太久。我完全忽略了这一点! – Brad 2012-03-29 14:35:38

错字..

Test-Path -path $path1 

应该

Test-Path -path $path2 
+0

变量名称不能在不带引号的情况下展开。 Test-Path -Path \\“$ server”\“$ filePath” – Tequila 2014-04-23 16:35:19

同时,为了安全起见,如果你要测试的目录只使用PathType参数:

Test-Path $path1 -PathType Container