2016-07-29 53 views
0

我正在編寫一個腳本,用於寫入並調用某些自己的函數。第一個功能我打電話是我記錄設置功能,在這裏我設置了這樣的日誌文件:-ErrorAction停止後腳本處理不會停止

function Create-Logfile { 
    if (!(Test-Path $Path)) { 

     try { 
      Write-Verbose "Write-Log: Creating $Path" 
      $NewLogFile = New-Item $Path -Force -ItemType File -ErrorAction stop 
     } catch { 
      Write-Verbose "Write-Log: Creating $Path failed: $($error[0].Exception.Message)" 
     } 

    } 

    write-host 'i do still execute' 
} 

function Do-Something{ 
    write-host 'doing something' 
} 

Create-LogFile #create the file 
write-host 'processing didnt stop' 
Do-Something 

如果該文件無法創建我想整個下面的腳本處理停止,但所有以下調用仍然處理。事件其他函數調用仍舊執行:(如果日誌文件創建失敗,我不想要任何東西去爲日誌文件是強制性的。

回答

1

既然你捕獲try catch塊中的終止錯誤,則必須在write-host命令後添加終止語句。根據您的需要(例如,退出,中斷等)有多種選擇(例如,退出,中斷等)

例如:

try 
{ 
    Write-Verbose "Write-Log: Creating $Path" 
    $NewLogFile = New-Item $Path -Force -ItemType File -ErrorAction stop 
} 
catch 
{ 
    Write-Verbose "Write-Log: Creating $Path failed: $($error[0].Exception.Message)" 
    exit 
} 

或者,您可以拋出自己的終止錯誤,如下所示:

throw "Write-Log: Creating $Path failed: $($error[0].Exception.Message)" 
1

你需要重新拋出錯誤..

function Create-Logfile { 
    if (!(Test-Path $Path)) { 

     try { 
      Write-Verbose "Write-Log: Creating $Path" 
      $NewLogFile = New-Item $Path -Force -ItemType File -ErrorAction stop 
     } catch { 
      Write-Verbose "Write-Log: Creating $Path failed: $($error[0].Exception.Message)" 
      Throw 
     } 

    } 

    write-host 'i do still execute' 
} 

function Do-Something{ 
    write-host 'doing something' 
} 

Create-LogFile #create the file 
write-host 'processing didnt stop' 
Do-Something