Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Get-Content: Try{ .. } catch { ..}?

I did

try {
    $g = Get-Content $file
} catch { 
    return ""
}

But the as soon as an another process still writes into $file (and blocks it) I get an error message: Can't access the file as..

Why am I not 'landing' in catch {} but getting the error - how can I check whether the file is accessible?

Thanks in advance, Golly

Got IT :)

I just use :

 try {
     $g = New-Object system.IO.StreamReader $file
 } catch { 
     return ""
 }

and in case the file is still written it redirects to the catch-branch

like image 880
gooly Avatar asked Jun 15 '14 12:06

gooly


Video Answer


1 Answers

In a Try/Catch the Catch block is only invoked on terminating errors. Use -ErrorAction Stop on your cmdlets to force all errors to be terminating:

try {
    $g = Get-Content $file -ErrorAction Stop
} catch { 
    return ""
}
like image 137
mjolinor Avatar answered Oct 19 '22 15:10

mjolinor