Bruno Bruno - 1 year ago 169
PowerShell Question

Elegant handling a dot-source failure in Powershell

So I have a script that is using dot-sourcing

$Dependencies = "Script1","Script2","Script3"
$Dependencies | % { . ".\$( $_ ).ps1" }

I have tried to use a
Try { } Catch { }
which caught the error but that imported the script into the scope of the try and catch.

What is the cleanest way of detecting a failure of the dot-source import?

Usually I can set the
to be
and that forces a function to throw an error but I don't seem to be able to do that with dot-sourcing.


In the end it turned out that try and catch did work. Here is my modified script

$Dependencies = "Script1","Script2","Script3"
$Dependencies |
ForEach-Object {
Try { . ".\$( $_ ).ps1" }
Catch { Throw }

Answer Source

I bet you used try-catch incorrectly. Take a look at following snippet (expanded for simplicity):

$Dependencies = "Script1","Script2","Script3"
$Dependencies | % {
    try {
        $psFile = ".\$($_).ps1"
        . $psFile
    } catch {
        Write-Host "Failed to execute $psFile"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download