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

时间:2013-08-15 20:54:43

标签: powershell

假设您拥有变量$source = "C:\temp\one\two\three"并且想要以编程方式将$destination设置为$destination = "C:\temp\one\two",那么您将如何做到这一点?

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

也许像

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

2 个答案:

答案 0 :(得分:23)

像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"

答案 1 :(得分:1)

$source = "C:\temp\one\two\three"
$dest = (new-object system.io.directoryinfo $source).parent.fullname

编辑:您可以使用DirectoryInfo为目录获取get-item,以便您可以这样做:

$dest = (get-item $source).parent.fullname