How to compare if a folder exists and if it does not exist, create her

Estevão França picture Estevão França · Apr 28, 2017 · Viewed 9.9k times · Source

I have the following problem, I need to create a script that compares if the directory exists and if it does not exist, create it. In the linux shell, I use the parameter -F to check if the directory exists. How do I test in PowerShell?

In Linux shell:

DIR=FOLDER

if [ -f $DIR ]
then
    echo "FOLDER EXIST";
else
    echo "FOLDER NOT EXIST";
    mkdir $DIR
fi

How do I make this comparison in Windows PowerShell?

$DIRE = "C:\DIRETORIO"

if ( -e $DIRE ) {
    echo "Directory Exists"
} else {
    md DIRETORIO
}

Answer

Martin Brandl picture Martin Brandl · Apr 28, 2017

You could also use the New-Item cmdlet with the force parameter, you don't even have to check whether the directory exists:

New-Item -Path C:\tmp\test\abc -ItemType Directory -Force