Tom
Tom

Reputation: 2230

Trim (or go up) one level of directory tree in powershell variable

Say you have the variable $source = "C:\temp\one\two\three" and you want to set $destination equal to $destination = "C:\temp\one\two" programmatically, how might you do it?

The best idea I've had would be to trim that, but is there a better way?

Perhaps something like

$source = "C:\temp\one\two\three"
$dest = "..$source"

Upvotes: 15

Views: 33521

Answers (2)

mikekol
mikekol

Reputation: 1862

Getting the parent from a DirectoryInfo object, like Lee suggests, will certainly work. Alternately, if you prefer to use more PowerShellesque commands as opposed to direct .NET Framework calls, you can use PowerShell's built-in Split-Path cmdlet like this:

$source      = "C:\temp\one\two\three"

$destination = Split-Path -Path $source -Parent

# $destination will be a string with the value "C:\temp\one\two"

Upvotes: 45

Lee
Lee

Reputation: 144136

$source = "C:\temp\one\two\three"
$dest = (new-object system.io.directoryinfo $source).parent.fullname

EDIT: You can get a DirectoryInfo for a directory using get-item so you can instead do:

$dest = (get-item $source).parent.fullname

Upvotes: 2

Related Questions