Most often when I am creating a directory in PowerShell I also want to navigate into that folder. I can do that on a single line like this.
New-Item -Path temp -ItemType Directory; Set-Location -Path temp
Or using aliases
md temp; cd temp
But that is just too much typing. So, I decided to create a function named mcd for make and change directory and have it loaded each time I start PowerShell. In this post I will explain how to do this.
First, we need to create the function. To do that I started Visual Studio code. I also installed the PowerShell extension for Code.
With Code ready I created a new file and changed the language mode from Plain Text to PowerShell. Copy and paste the code below into the file.
function mcd {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
$Path
)
New-Item -Path $Path -ItemType Directory
Set-Location -Path $Path
}
Save the file so you we can dot source the file in our PowerShell profile. I named my file utils.ps1 and saved it in C:\Users\me\Documents\WindowsPowerShell\Scripts.
Now we must update our profile to dot source the file we just created. Start PowerShell and type the following:
code $Profile
This will start Code with your current profile script loaded or create a new file for you if you do not already have one.
Add to the bottom of the file
. C:\Users\me\Documents\WindowsPowerShell\Scripts\utils.ps1
Now just save and close the file. Now every new PowerShell session you start you will be able to use mcd to create and navigate into a folder.
PS C:\> mcd test
Directory: C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2/3/2018 11:41 AM test
PS C:\test>