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

标签 powershell

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

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

也许像

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

最佳答案

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

关于powershell - 在 powershell 变量中修剪(或上升)一级目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261658/

相关文章:

powershell - 使用powershell创建计划任务而不存储密码

powershell - 如何在powershell中复制名称中包含变量的文件?

powershell - 直接在jenkins管道中执行powershell命令

powershell - 如何在Powershell中为高级功能生成非终止错误

python - 找不到关于 Python 的 read() 方法的任何信息 (python 2.7)

git - 使用 Windows PowerShell 设置 .SSH key 时出错

azure - Powershell 函数 -WhatIf 用于没有 -WhatIf 支持的 cmdlet?

powershell - Powershell将参数传递到功能链中

powershell - 我的简单启用和禁用帐户 powershell 代码无法正常工作

powershell - 如何在powershell中修剪文件中的所有行