如何在 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 參數僅獲取葉的擴展名。

命令:

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

輸出:

.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 "\"

拆分方法在上面腳本中的分隔符 \ 上拆分路徑字串。然後通過管道傳遞到 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