PowerShell 拆分目錄路徑

Rohan Timalsina 2023年1月30日
  1. 在 PowerShell 中使用 Split-Path Cmdlet 拆分目錄或檔案路徑
  2. 在 PowerShell 中使用 Split() 方法來分割目錄或檔案路徑
PowerShell 拆分目錄路徑

在 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 中拆分路徑的示例。我們還向你展示瞭如何使用 \ 分隔符加入路徑。

作者: 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