2014-07-01 32 views
1

這是Powershell腳本的一小塊,爲了遞歸獲取所有文件夾/子文件夾和文件,我不能使用Get-ChildItem,因爲它在UNC網絡路徑上速度太慢,所以我的想法是使用使用PSSession遠程執行[Microsoft.VisualBasic.FileIO.FileSystem]::GetFiles,並且它工作。Try Catch statement is breaking my code

通過使用PsSession遠程執行此代碼,我的try/catch語句完美運行,我可以將結果變爲$GetRemoteFolderCheck變量。

$path_folder = "C:\sources\sql" 

    $session = New-PSSession -ComputerName $ipsqlserver -Credential $credentials 
     Invoke-Command -Session $session -ScriptBlock { 
     [reflection.assembly]::loadwithpartialname("Microsoft.VisualBasic") | Out-Null 
     } 

     $GetRemoteFolderCheck = Invoke-Command -Session $session -ScriptBlock { 
      try 
      { 
      [Microsoft.VisualBasic.FileIO.FileSystem]::GetFiles(
      $using:path_folder, 
      [Microsoft.VisualBasic.FileIO.SearchOption]::SearchAllSubDirectories) 
      } 
      catch 
      { 
       return $_ 
      } 
     } 

但是,當我在本地執行相同的代碼,而無需使用PSSession時,它不工作,它打破我的代碼......因爲Write-Host沒有在我的殼顯示

$path_folder = "C:\sources\sql" 

$GetLocalFolderCheck = try{[Microsoft.VisualBasic.FileIO.FileSystem]::GetFiles(
     $path_folder, 
     [Microsoft.VisualBasic.FileIO.SearchOption]::SearchAllSubDirectories) } 
     catch 
     { 
      return $_ 
     } 

    Write-Host "toto" 

我不不明白爲什麼它不能按預期工作,我的$GetlocalFolderCheck應該包含異常,並且不會破壞我的代碼。

感謝您的幫助

回答

2

由於您使用return聲明這是預期的行爲。 Write-Host "toto"實際上無法訪問,因爲無論您的調用是成功還是引發錯誤,都會返回值。如果這個C#代碼,將會有編譯警告Unreachable code detected

您應該能夠通過改變catch塊,以達到預期的效果:

... 
catch 
     { 
      $_ 
     } 
... 

這樣,如果有錯誤,它會向上傳遞管道爲對象,以及執行將繼續。

+0

非常感謝。初學者錯誤:) –