如何在 PowerShell 中拆分目录路径

  1. 使用 Split-Path Cmdlet 拆分 PowerShell 中的目录或文件路径
  2. 使用 Split() 方法拆分 PowerShell 中的目录或文件路径
如何在 PowerShell 中拆分目录路径

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

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

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

Split-Path cmdlet 返回 PowerShell 中给定路径的特定部分。路径的部分可以是父文件夹、子文件夹、文件名或仅文件扩展名。

默认情况下,Split-Path 返回路径的父文件夹。下面的例子将显示 C:\Windows\System32,即 notepad.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 参数仅获取叶的扩展名。

命令:

{CODE_BLOCK_8}

输出:

.exe

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

命令:

Split-Path HKCU:\Software\Microsoft

输出:

HKCU:\Software

使用 Split() 方法拆分 PowerShell 中的目录或文件路径

要将字符串拆分为数组,请使用 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 中拆分路径的示例。我们还向您展示了如何使用 \ 分隔符连接路径

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Rohan Timalsina
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

相关文章 - PowerShell Path