2016-11-30 37 views
1

我需要在SQL作業中檢查是否存在某個路徑上的文件,因此如果存在文件,則停止進一步執行。喜歡的東西:CMDExec如果存在然後停止

$file = "\\networklocation\file.bak" 
if (-exists (Test-Path $file)) 
{ 
    throw "$file not found." 
} 

回答

3

只是省略-exists開關,確保$ErrorActionPreference設置爲stop

$ErrorActionPreference = 'stop' 
$file = "\\networklocation\file.bak" 
if (Test-Path $file) 
{ 
    throw "$file found." 
} 
+0

爾......如果文件確實存在,我想他會停下來。 –

+0

@WalterMitty你是對的。將編輯我的答案 - 只是想知道爲什麼他拋出一個異常,如果該文件不存在(多數民衆贊成在實際的狀態,他期待)... –

+1

好吧,解釋它。有一些備份/恢復工作在這個機制上工作:1.從產品中取得備份2.在辦公區域恢復它3.刪除可以根據用戶請求重新做的備份文件。不是我的邏輯傢伙 –

0

測試路徑cmdlet返回布爾和你差不多有:

$file = "\\networklocation\file.bak" 
if (Test-Path $file) 
{ 
    throw "$file not found." 
}