pizzim13
pizzim13

Reputation: 1482

PowerShell: How to check for multiple conditions (folder existence)

I am in the process of writing a script to make changes to folder permissions. Before it does that I would to do some checking to make sure that I am working in the correct directory. My problem is how do I check to see if four subfolders (i.e. Admin, Workspace, Com, & Data) exists before the script progresses. I assume I would be using Test-Path on each directory.

Upvotes: 9

Views: 19853

Answers (3)

montonero
montonero

Reputation: 1761

Test-Path can check multiple paths at once. Like this:

Test-Path "c:\path1","c:\path2"

The output will be an array of True/False for each corresponding path.

This could be especially helpful if you have a lot of files/folders to check.

Check if all paths are exists:

if ((Test-Path $arraywithpaths) -notcontains $false) {...}

Same way for the non-existence:

if ((Test-Path $arraywithpaths) -contains $false) {...}

Upvotes: 1

Simon Catlin
Simon Catlin

Reputation: 2229

Hint:

Remember to specify -LiteralPath - stops any possible misinterpretation. I've "been there" (so to speak) with this one, spending hours debugging code.

Upvotes: 2

JaredPar
JaredPar

Reputation: 755557

What's wrong with the following?

if ( (Test-Path $path1) -and (Test-Path $path2) ) { 

}

Upvotes: 14

Related Questions