2012-03-29 159 views
0

代碼(底部)來自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

回答

2

錯字..

Test-Path -path $path1 

應該

Test-Path -path $path2 
+0

變量名稱不能在不帶引號的情況下展開。 Test-Path -Path \\「$ server」\「$ filePath」 – Tequila 2014-04-23 16:35:19

1

同時,爲了安全起見,如果你要測試的目錄只使用PathType參數:

Test-Path $path1 -PathType Container 
相關問題