PS: Build A Path Dynamically

1 minute read

Description:

So just for learning purposes, I wanted to create a function that creates all directories leading up to a path if you just pass a path’s name as a parameter. We all know that adding a “-Force” to New-Item will do this for you, but still…

To Resolve:

  1. First, we want to create a path:
1
$Path = "HKCU:\SOFTWARE\Microsoft\Office\15.0\Outlook\AutoDiscover"
  1. Next, split it into parts. This is important because paths will have different levels. For example, C:\scripts\mydir is two levels deep and c:\scripts\mydir\hello\world is four levels deep. We want the function to be able to dynamically create these directories for us.
1
$PathList = $Path -split '\\'
  1. Next, we want to initiate an array to put each into:
1
$NewPath = ''
  1. Now we create a loop to create the directories
1
2
3
4
5
6
7
8
foreach ($p in $PathList) 
{
    $NewPath += "$p\"
    if (-not(Test-Path $NewPath)) 
    {
        New-Item -ItemType Directory -Path $NewPath | Out-Null
    }
}
  1. What this loop does is add each part of the path, $p, into the $NewPath array. It then creates that part of the path if it doesn’t exist already. So the first iteration will create HKCU:; but this obviously exists so it will skip to the next one HKCU:\SOFTWARE and so on until it has stepped through all directories.

Comments