9

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
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Estevão França
  • 115
  • 1
  • 1
  • 5

2 Answers2

11

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
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • 1
    When `-force`d, what happens to an already-extant directory? I generally do not recommend blindly `-force`ing a cmdlet to 'do its thing' unless I specifically want to force a known state. – Jeff Zeitlin Apr 28 '17 at 13:58
  • @JeffZeitlin You are right, maybe I shouldn't recommend it in first place but Ansgar already provided the right comment. Just wanted to bring up another way to do this which also works (even if the directory already exists). – Martin Brandl Apr 28 '17 at 14:03
  • if the folder already exists, it carries the command out anyway without affecting it.As in, it doesn't overwrite the folder, because it doesn't need to. It doesn't affect the contents of the folder if it already exists either. – Ross Lyons Apr 28 '17 at 15:41
  • 4
    The command as suggested in answer above is the equivalent to telling PowerShell *Get me a folder object for the path 'C:\tmp\test\abc'. If it already exists, great; if not, create it, and give me that object. I don't care how you do it, just don't delete anything, and make it happen.* I use it in scripts, and it is a clean, safe way to ensure a path exists without causing any harm to existing files or folders. This appears to be exactly what the OP's intent was, even if it's not what they asked for. – TheMadTechnician Apr 28 '17 at 18:09
  • @TheMadTechnician Thanks for clarify that and for the feedback! – Martin Brandl Apr 28 '17 at 18:19
  • Thanks for the help! – Estevão França Apr 29 '17 at 18:38
8

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.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68