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:


 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
    [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


Comments have been disabled for this content.