2010-02-02 4 views
125

Ceci est le try catch dans PowerShell 2,0prises Powershell 2.0 try comment accéder à l'exception

$urls = "http://www.google.com", "http://none.greenjump.nl", "http://www.nu.nl" 
$wc = New-Object System.Net.WebClient 

foreach($url in $urls) 
{ 
    try 
    { 
     $url 
     $result=$wc.DownloadString($url) 
    } 
    catch [System.Net.WebException] 
    { 
     [void]$fails.Add("url webfailed $url") 
    } 
} 

mais ce que je veux faire quelque chose comme dans C#

catch(WebException ex) 
{ 
    Log(ex.ToString()); 
} 

Est-ce possible?

Répondre

178

Essayez quelque chose comme ceci:

try { 
    $w = New-Object net.WebClient 
    $d = $w.downloadString('http://foo') 
} 
catch [Net.WebException] { 
    Write-Host $_.Exception.ToString() 
} 

L'exception est dans la variable $_. Vous pouvez explorer $_ comme ceci:

try { 
    $w = New-Object net.WebClient 
    $d = $w.downloadString('http://foo') 
} 
catch [Net.WebException] { 
    $_ | fl * -Force 
} 

Je pense qu'il vous donnera toutes les informations dont vous avez besoin.

Ma règle: s'il y a des données qui ne sont pas affichées, essayez d'utiliser -force.

Questions connexes