When creating and working with directories in PowerShell and Command Prompt, you may encounter errors when trying to create a new directory using the mkdir command. In best practice, we don’t want commands to throw exceptions or set error flags, as they can cause issues further down the script if not handled correctly. The best course of action is to prevent the error from occuring from the first place. In this article, we’ll go over how to prevent the errors.
Solution Summary
- PowerShell: use
-Forceargument withNew-Itemormkdir - Command Prompt: use snippet
if not exist <newDir>\NUL mkdir <newDir>
PowerShell: New-Item without error message
In PowerShell, New-Item is the command for the alias mkdir. So we’ll refer to it as New-Item. Let’s start with what happens in PowerShell if we try to create a directory named foo that already exists:
New-Item foo
Output (from the CLI. If from script a similar but more extensive message is shown):
New-Item: An item with the specified name C:\foo already exists.
We can also get a copy of the New-Item cmdlet error message by using -ErrorVariable:
New-Item foo -ErrorVariable errorInfo
Write-Host $errorInfo
Now, $errorInfo will contain error message An item with the specified name C:\foo already exists..
To avoid this error, we can simply use the -Force argument with the command. This will create the directory and if it exists will not show or set an error. In powershell:
New-Item foo\bar -Force
If there are files already in the directory, the files are unaffected.
Command Prompt: mkdir without error message
Similarily, if done in command prompt:
mkdir foo
Output:
A subdirectory or file foo already exists.
mkdir in command prompt does not have -Force argument. What to do? We can check with exist.
Lets do the equivalent to mkdir foo -Force in Command Prompt and in a .bat batch file by the following:
if not exist foo\NUL mkdir foo
This works because NUL always exists on a local MS-DOS FAT drive; therefore, if C:\foo\ exists, C:\foo\NUL exists. This technique can also be used to verify that a drive exists. Does not work with network devices.