Alex Bazuvul
Alex Bazuvul

Reputation: 65

How to do string splitting

How can I split a string?

I would like to turn C:\RoamingFiles\D\file.txt to D:\file.txt.

I'm not sure how to do it, as split won't filter out C:\RoamingFiles\ as I want.

Upvotes: 0

Views: 223

Answers (3)

Josef Nemec
Josef Nemec

Reputation: 688

This should work just fine (including sub-folders):

$fullPath = "C:\RoamingFiles\D\test\test2\file.txt"
$baseFolder = "C:\RoamingFiles\" -replace "\\", "\\"
$fullPath -match "$baseFolder([a-z]\\.+)" | Out-Null
Write-Host $matches[1].Insert(1, ":")

Upvotes: 0

Joey
Joey

Reputation: 354854

I'm a little confused as to what exactly you want -split to do here. It seems like

$myString -replace '^C:\\RoamingFiles\\([^\\]+)\\', '$1:\'

would work better for what you seem to be doing there. This essentially replaces the path component C:\RoamingFiles\ with the drive letter that follows. But this is all pretty much guesswork since you gave only one example.

Upvotes: 2

Mithrandir
Mithrandir

Reputation: 25397

Tried this use [System.IO.Path]?

$name = "C:\RoamingFiles\file.txt"
$shortname =  [System.IO.Path]::GetFileName($name)
$newname =  [System.IO.Path]::Combine("D:\", $shortname)
echo $newname

Upvotes: 1

Related Questions