如何在PowerShell中规范化路径? [英] How to normalize a path in PowerShell?

查看:67
本文介绍了如何在PowerShell中规范化路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两条路径:

fred\frog

..\frag

我可以像这样将它们加入PowerShell中:

I can join them together in PowerShell like this:

join-path 'fred\frog' '..\frag'

这给了我这个

fred\frog\..\frag

但是我不想要那样.我想要一个没有双点的归一化路径,像这样:

But I don't want that. I want a normalized path without the double dots, like this:

fred\frag

我怎么能得到那个?

推荐答案

您可以使用pwdJoin-Path[System.IO.Path]::GetFullPath的组合来获取完全限定的扩展路径.

You can use a combination of pwd, Join-Path and [System.IO.Path]::GetFullPath to get a fully qualified expanded path.

由于cd(Set-Location)不会更改进程当前的工作目录,因此只需将相对文件名传递给无法理解PowerShell上下文的.NET API,可能会产生意想不到的副作用,例如解析到基于初始工作目录(而不是当前位置)的路径.

Since cd (Set-Location) doesn't change the process current working directory, simply passing a relative file name to a .NET API that doesn't understand PowerShell context, can have unintended side-effects, such as resolving to a path based off the initial working directory (not your current location).

您要做的是首先确定自己的道路:

What you do is you first qualify your path:

Join-Path (Join-Path (pwd) fred\frog) '..\frag'

这会产生(鉴于我当前的位置):

This yields (given my current location):

C:\WINDOWS\system32\fred\frog\..\frag

使用绝对基数,可以安全地调用.NET API GetFullPath:

With an absolute base, it is safe to call the .NET API GetFullPath:

[System.IO.Path]::GetFullPath((Join-Path (Join-Path (pwd) fred\frog) '..\frag'))

其中给出了完全限定的路径,并且删除了..:

Which gives you the fully qualified path and with the .. removed:

C:\WINDOWS\system32\fred\frag

这也并不复杂,就我个人而言,我不赞成依赖于外部脚本的解决方案,这是一个简单的问题,可以通过Join-Pathpwd恰当地解决(GetFullPath只是为了使其美观).如果只想保留相对部分,只需添加.Substring((pwd).Path.Trim('\').Length + 1)并瞧瞧!

It's not complicated either, personally, I disdain the solutions that depend on external scripts for this, it's simple problem solved rather aptly by Join-Path and pwd (GetFullPath is just to make it pretty). If you only want to keep only the relative part, you just add .Substring((pwd).Path.Trim('\').Length + 1) and voila!

fred\frag

更新

感谢@Dangph指出C:\边缘情况.

这篇关于如何在PowerShell中规范化路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆