Knight Talks Tech

Split a filepath with PowerShell

This is a relatively short post as the process is simple but may be required in more complex scenarios.

$dirArray = ("C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA").Split('\')
foreach ($dir in $dirArray)
{
  $dir
}

By calling the Split function we get a zero-based array ($dirArray) containing each element of the supplied string based on the delimiter (‘\’). This array is dynamically sized and each element can be accessed sequentially, as in the above example, or directly.
This example will count the number of elements in the array and then output the chosen element.

$dirArray = ("C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA").Split('\')
$dirArray.Count
$dirName = $dirArray[$dirArray.Count-2]

The output from this will be “MSSQL”.

Exit mobile version