PowerShell: "Cleaning" a path name, searching for smarter solution...

When you construct a path in powershell with for example Join-Path, you can get things like ".."in your path.

For example:

Join-Path -Path "c:\program files" -ChildPath "..\Temp"

results in:

"c:\program files\..\Temp"

Instead of:

"c:\Temp"

 I had to solve this problem, and now came up with the below dirty solution. Any cleaner solutions are appreciated;-)

 

# CleanPathName
# Clean a given path from elements like .. in the path and trailing '\',
# so c:\program files\..\temp\ becomes c:\temp.
# The given Path must exist.
# Should be rewritten if a cleaner approach is found
function global:CleanPathName
{
  param
  (
    [string]$path = $(throw "Missing: path")
  )
  $orgLocation = Get-Location
  Set-Location -Path $path
  $cleanPath = Get-Location
 

# restore original location
  Set-Location -Path $orgLocation

  return $cleanPath.Path
}

Published Monday, December 18, 2006 1:37 AM by svdoever
Filed under: ,

Comments

Monday, December 18, 2006 2:27 AM by Martin

# re: PowerShell: "Cleaning" a path name, searching for smarter solution...

What about

[system.io.path]::GetFullPath($path)

However, it always returns an absolute path and won't work with relative paths.

Monday, December 18, 2006 6:50 AM by svdoever

# re: PowerShell: "Cleaning" a path name, searching for smarter solution...

Hi Martin, thanks! That does exactly the job, and is way, way cleaner than my solution;-) I knew it was somewhere in the .NET framework, but where... ;-)

Monday, December 18, 2006 7:34 AM by /\/\o\/\/

# re: PowerShell: "Cleaning" a path name, searching for smarter solution...

I would think that

resolve-path

NAME

   Resolve-Path

SYNOPSIS

   Resolves the wildcard characters in a path and displays the path contents.

should take care of this (it does not)

Greetings /\/\o\/\/

Monday, December 18, 2006 4:34 PM by svdoever

# re: PowerShell: "Cleaning" a path name, searching for smarter solution...

Hi MoW, that suprised me as well... was the first think I looked into..

Leave a Comment

(required) 
(required) 
(optional)
(required)