PowerShell for Windows Admins

Aug 10 2018   7:21AM GMT

Create a directory with PowerShell

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


I was recently asked how you can create a directory with PowerShell

Using the command prompt you’d do this

c:\Scripts> md c:\Test0908

c:\Scripts>dir c:\test*
Volume in drive C has no label.
Volume Serial Number is DAA0-D709

Directory of c:\

09/07/2018 11:20 <DIR> test
09/08/2018 15:22 <DIR> Test0908
01/11/2017 11:59 <DIR> TestCIM
01/03/2018 13:36 <DIR> testmodule
25/04/2018 21:33 <DIR> TestScripts
0 File(s) 0 bytes
5 Dir(s) 147,528,462,336 bytes free

The same is true of PowerShell

PS> md c:\test090801

Directory: C:\

Mode LastWriteTime Length Name
—- ————- —— —-
d—– 09/08/2018 15:23 test090801

PS> dir c:\test*

Directory: C:\

Mode LastWriteTime Length Name
—- ————- —— —-
d—– 09/07/2018 11:20 test
d—– 09/08/2018 15:22 Test0908
d—– 09/08/2018 15:23 test090801
d—– 01/11/2017 10:59 TestCIM
d—– 01/03/2018 12:36 testmodule
d—– 25/04/2018 21:33 TestScripts

However, md is an alias of mkdir

PS> Get-Command md

CommandType Name
———– —-
Alias md –> mkdir

If you dig into mkdir you’ll find that its a function

PS> Get-Command mkdir

CommandType Name
———– —-
Function mkdir

Looking into the definition of the mkdir function

PS> Get-Command mkdir | select -expand Definition

you’ll see that it uses New-Item. The actual code that does the work is:

$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(‘New-Item’,
$scriptCmd = {& $wrappedCmd -Type Directory @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline()

The important parts are that its using New-Item with a type of Directory

This leads to using New-Item directly

PS> New-Item -Path C:\ -Name Test090802 -Type Directory

Directory: C:\

Mode LastWriteTime Length Name
—- ————- —— —-
d—– 09/08/2018 15:36 Test090802


PS> New-Item -Path C:\Test090803 -Type Directory

Directory: C:\

Mode LastWriteTime Length Name
—- ————- —— —-
d—– 09/08/2018 15:36 Test090803

I always prefer to give the parent path and the name as it’s a more explicit statement of what I’m doing.

One thing to note is that you can create the whole path to a nested folder in one pass:

PS> New-Item -Path C:\Test090804\test090805 -Type Directory

Directory: C:\Test090804

Mode LastWriteTime Length Name
—- ————- —— —-
d—– 09/08/2018 15:38 test090805

The command creates test090804 and then test090805 as a subfolder of test090804.

In case you were wondering dir is an alias of Get-ChildItem

PS> Get-Alias dir

CommandType Name
———– —-
Alias dir -> Get-ChildItem

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: