Make Sure Folder Exists

by Jul 5, 2011

To ensure that a given folder exists, you can stick to trial-and-error, and hide error messages:

New-Item c:\somefolder\anotherfolder\yetanother -ItemType Directory -ea 0 | Out-Null

 

This will create all missing folders and hide all error messages. If you can't create the folder due to other reasons such as missing privileges, you would not get a warning, though. A more sophisticated way uses a simple condition and Test-Path:

$folder = 'C:\somefolder\anotherfolder\yetanother' 
if ( -not (Test-Path $folder) ) {New-Item $folder  -Type Directory  | Out-Null}

 

Twitter This Tip!
ReTweet this Tip!