PowerShell Custom Drives
A custom drive is a short name that points at a folder on disk. It lets a script work inside that folder through the short name.
Map a folder to a drive name
Build a folder under the script folder and fill it with files. Then map it to the name Demo and list its files from inside the drive.
$root = Join-Path $PSScriptRoot 'DemoData'
New-Item -ItemType Directory -Path $root | Out-Null
Set-Content -Path (Join-Path $root 'b.txt') -Value 'bee'
Set-Content -Path (Join-Path $root 'a.txt') -Value 'aye'
New-PSDrive -Name Demo -PSProvider FileSystem -Root $root | Out-Null
Set-Location Demo:
Get-ChildItem -Filter *.txt | Sort-Object Name | Select-Object -ExpandProperty NameRead back the mapped drive name
Get-PSDrive with the drive name finds the mapped drive. Print only its Name, never the whole drive object.
$root = Join-Path $PSScriptRoot 'DemoData'
New-Item -ItemType Directory -Path $root | Out-Null
New-PSDrive -Name Demo -PSProvider FileSystem -Root $root | Out-Null
Get-PSDrive -Name Demo | Select-Object -ExpandProperty NameRemove a drive and prove it is gone
Remove-PSDrive removes the mapping. A later Get-PSDrive for the name returns nothing, so the guarded line prints.
$root = Join-Path $PSScriptRoot 'DemoData'
New-Item -ItemType Directory -Path $root | Out-Null
New-PSDrive -Name Demo -PSProvider FileSystem -Root $root | Out-Null
Remove-PSDrive -Name Demo
$check = Get-PSDrive -Name Demo -ErrorAction SilentlyContinue
if ($null -eq $check) { 'removed' }Example
$root = Join-Path $PSScriptRoot 'DemoData'
New-Item -ItemType Directory -Path $root | Out-Null
Set-Content -Path (Join-Path $root 'c.txt') -Value 'cee'
Set-Content -Path (Join-Path $root 'a.txt') -Value 'aye'
Set-Content -Path (Join-Path $root 'b.txt') -Value 'bee'
New-PSDrive -Name Demo -PSProvider FileSystem -Root $root | Out-Null
Set-Location Demo:
Get-ChildItem -Filter *.txt | Sort-Object Name | Select-Object -ExpandProperty Name
Set-Location $PSScriptRoot
Remove-PSDrive -Name Demo
$check = Get-PSDrive -Name Demo -ErrorAction SilentlyContinue
if ($null -eq $check) { 'removed' }Key points
- Custom drive: a short name that points at a folder on disk.
- Use New-PSDrive to map a drive name to a folder.
- Use Set-Location Demo: to move into the mapped drive.
- Use Get-ChildItem inside the drive to list the files in its folder.
- Use $PSScriptRoot to refer to the folder holding the running script.
- Use Remove-PSDrive to remove a mapped drive.
In this example, the script builds a DemoData folder with three files, maps it to Demo, moves into the drive and lists its files in name order, moves back to the script folder, removes the drive, and prints removed once the check shows the drive is gone.
Note
removing a drive does not delete the folder or its files.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which command removes the Demo drive you mapped?