0

I am new at Powershell and I have spent a whole day working out this how to split a string I have this string path

RootFolder\Subfolder1\SubFolder2\SubFolder3

I want to split this into two strings so that the first string holds the RootFolder and the second string has rest of the string.

E.g: RootFolder\Subfolder1\SubFolder2\SubFolder3

$rootFolder = RootFolder 
$subFolders = Subfolder1\SubFolder2\SubFolder3

Thanks in advance!

2
  • 3
    $root, $path = "RootFolder\Subfolder1\SubFolder2\SubFolder3".Split("\", 2) leaves you with $root # --> RootFolder and $path # --> Subfolder1\SubFolder2\SubFolder3 Commented May 13, 2021 at 13:27
  • 1
    there is a cmdlet for that >>> Get-Help Split-Path -Parameter * <<< [grin] look specifically at 'qualifier', 'parent', & 'leaf'. also, if the item is a FileInfo or DirInfo object, look at the .Root, .Parent, and .Directory.Parent properties. Commented May 13, 2021 at 13:50

2 Answers 2

1

One option is to use the split operator:

$splitPath = 'RootFolder\Subfolder1\SubFolder2\SubFolder3' -split '\\', 2

Which gives this output:

$splitPath

RootFolder
Subfolder1\SubFolder2\SubFolder3

You can access the individual parts like this:

$splitPath[0]

RootFolder

If the path begins with a drive letter (e.g. C:\RootFolder\Subfolder1\SubFolder2\SubFolder3) and you want to ignore it, just increase the substring count:

$splitPath = 'C:\RootFolder\Subfolder1\SubFolder2\SubFolder3' -split '\\', 3


$splitPath

C:
RootFolder
Subfolder1\SubFolder2\SubFolder3
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your help !
1

Here's a few methods for you:

Using the string's Split() method

$root, $path = "RootFolder\Subfolder1\SubFolder2\SubFolder3".Split("\", 2)

$root # --> RootFolder
$path # --> Subfolder1\SubFolder2\SubFolder3

Using the string's IndexOf() method

$folder = "RootFolder\Subfolder1\SubFolder2\SubFolder3"
$index = $folder.IndexOf("\")
$root  = $folder.Substring(0, $index)
$path  = $folder.Substring($index + 1)

$root # --> RootFolder
$path # --> Subfolder1\SubFolder2\SubFolder3

Or even something like

$folder = "RootFolder\Subfolder1\SubFolder2\SubFolder3" -split '\\'
$root   = $folder[0]
$path   = $folder[1..($folder.Count -1)] -join '\'

$root # --> RootFolder
$path # --> Subfolder1\SubFolder2\SubFolder3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.