Skip to content

Split a filepath with PowerShell

10/11/2016

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”.

Advertisements

From → Powershell

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: