Gus
Gus

Reputation: 943

powershell pass variables throw try/catch

I'm trying to use try / catch with the if statement to verify that a directory exists (I hope this is a correct solution!?), but I have a problem setting and passing the value of the $RepoDir variable into the catch statement

try {

    if (Notexists -Path $RepoDoc) {
       $RepoDir = "a"
       -ErrorAction Stop
    } 
    if (Notexists -Path $RepoExcel) {
       $RepoDir = "b"
       -ErrorAction Stop
    }
    if (Notexists -Path $RepoAttach) {
       $RepoDir = "c"
       -ErrorAction Stop
    }
}
catch {
   Write-Host "Directory $RepoDir not exist !" ---> Directory not exist ! 
   break
}

Is it a scope problem?
How could I do that?
Thank you

Upvotes: 0

Views: 1465

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

A proper way of doing what you want would be something like this:

$RepoDoc, $RepoExcel, $RepoAttach | Where-Object {
    -not (Test-Path -LiteralPath $_)
} | ForEach-Object {
    "Directory ${_} does not exist."
}

Upvotes: 2

Related Questions