迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 >

PowerShell 拆分目录路径

作者:迹忆客 最近更新:2024/02/01 浏览次数:

在 PowerShell 中使用路径时,有时你可能需要拆分目录或文件路径。PowerShell 有一个方便的 cmdlet Split-Path,可让你将路径拆分为父路径、子文件夹或文件名。

本教程将教你在 PowerShell 中拆分目录或文件路径。


在 PowerShell 中使用 Split-Path Cmdlet 拆分目录或文件路径

Split-Path cmdlet 在 PowerShell 中返回一个给定路径的特定部分。路径的一部分只能是父文件夹、子文件夹、文件名或文件扩展名。

默认情况下,Split-Path 返回路径的父文件夹。以下示例将显示 C:\Windows\System32notepad.exe 的父文件夹。

命令:

Split-Path -Path "C:\Windows\System32\notepad.exe"

输出:

C:\Windows\System32

-Qualifier 参数显示路径的限定符。限定符是路径的驱动器,例如 C:D:

命令:

Split-Path -Path "C:\Windows\System32\notepad.exe" -Qualifier

输出:

C:

-Leaf 参数打印路径的最后一项。

命令:

Split-Path -Path "C:\Windows\System32\notepad.exe" -Leaf

输出:

notepad.exe

要显示叶子的基本名称,请使用 LeafBase 参数。它返回不带扩展名的文件名。

命令:

Split-Path -Path "C:\Windows\System32\notepad.exe" -LeafBase

输出:

notepad

你可以使用 -Extension 参数来仅获取叶扩展。

命令:

Split-Path -Path "C:\Windows\System32\notepad.exe" -Extension

输出:

.exe

你还可以使用 Split-Path 拆分注册表路径的路径。

命令:

Split-Path HKCU:\Software\Microsoft

输出:

HKCU:\Software

在 PowerShell 中使用 Split() 方法来分割目录或文件路径

要将字符串划分为数组,请使用 Split() 方法。你可以使用此方法将路径字符串拆分为数组。

然后,你可以使用 Select-Object 选择数组中的特定位置并将它们连接为路径。以下示例将路径 C:\Windows\System32\notepad.exe 拆分为 C:\Windows

命令:

$path = "C:\Windows\System32\notepad.exe".Split("\") | Select-Object -First 2
$path -join "\"

split 方法在上述脚本中的分隔符 \ 上拆分路径字符串。然后通过管道传送到 Select-Object,仅从数组中选择前两个对象。

第一个命令的结果存储在变量 $path 中。第二个命令将 $path 中的结果对象与\ 连接起来并创建一个新路径。

输出:

C:\Windows

以下示例将路径 C:\Windows\System32\notepad.exe 拆分为 System32\notepad.exe

命令:

$path = "C:\Windows\System32\notepad.exe".Split("\") | Select-Object -Last 2
$path -join "\"

输出:

System32\notepad.exe

假设你需要路径中的第二个和最后一个元素。然后你可以使用 -Index 参数选择数组中的特定位置。

-Index 参数选择索引 13。数组中的索引值从 0 开始。

命令:

$path = "C:\Windows\System32\notepad.exe".Split("\") | Select-Object -Index 1,3
$path -join "\"

输出:

Windows\notepad.exe

在本文中,我们学习了几个在 PowerShell 中拆分路径的示例。我们还向你展示了如何使用 \ 分隔符加入路径。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 Windows PowerShell 中获取命令行参数

发布时间:2024/03/04 浏览次数:358 分类:编程语言

本文将解释我们如何使用 PowerShell 的参数函数处理命令行参数,参数如何工作,我们如何使用 PowerShell 参数将值传递给参数,以及定义参数的基本方法是什么。

Windows PowerShell 中的 Base64 编码

发布时间:2024/03/04 浏览次数:332 分类:编程语言

本文将展示如何编码和解码 base64 字符串。Windows PowerShell 当前版本没有本机命令,因此我们将向你展示如何执行此操作的替代方法。

在 Windows PowerShell 中写入输出

发布时间:2024/03/04 浏览次数:259 分类:编程语言

本文将向你展示如何在 Windows PowerShell 中编写或打印输出。本文还将区分多个 write cmdlet 并解释它们的意义。

在 PowerShell 中注释代码

发布时间:2024/03/04 浏览次数:363 分类:编程语言

本文将展示在 Windows PowerShell 中注释代码的多种方法。本文还介绍了注释代码时的一些最佳实践。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便