Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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"
like image 933
Tom Avatar asked Aug 15 '13 20:08

Tom


2 Answers

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"
like image 111
mikekol Avatar answered Oct 10 '22 09:10

mikekol


$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
like image 24
Lee Avatar answered Oct 10 '22 08:10

Lee