在powershell变量中修剪(或上升)一级目录树

Tom*_*Tom 4 powershell

假设你有变量$source = "C:\temp\one\two\three"并且你想要$destination$destination = "C:\temp\one\two"编程方式设置等于,你怎么能这样做?

我所拥有的最好的想法是修剪它,但有更好的方法吗?

也许是这样的

$source = "C:\temp\one\two\three"
$dest = "..$source"
Run Code Online (Sandbox Code Playgroud)

mik*_*kol 25

像Lee建议的那样从DirectoryInfo对象中获取父级肯定会起作用.或者,如果您更喜欢使用更多PowerShellesque命令而不是直接使用.NET Framework,则可以使用PowerShell的内置Split-Path cmdlet,如下所示:

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

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

# $destination will be a string with the value "C:\temp\one\two"
Run Code Online (Sandbox Code Playgroud)