Search code examples
powershellscriptingpowershell-3.0windows-scripting

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


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
}

Solution

  • Per the comments, Test-Path is the PowerShell cmdlet you should use to check for the existence of a file or directory:

    $DIRE = "C:\DIRETORIO"
    
    if ( Test-Path $DIRE ) {
        echo "Directory Exists"
    } else {
        md DIRETORIO
    }
    

    The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element.