如何在 PowerShell 中使用 Push-Location 和 Pop-Location 命令?


PowerShell 中的 **Push-Location** 命令用於將當前位置推入(新增)位置棧(後進先出 (LIFO) - 佇列),而 **Pop-Location** 用於從棧中檢索最後一個位置。

當 PowerShell 控制檯開啟時,棧中沒有設定任何位置。

PS C:\> Get-Location -Stack
PS C:\>

當您鍵入 **Push-Location** 命令時,它會同時執行兩個操作。首先,它將當前位置儲存到棧頂,其次,它會瀏覽指定的路徑。如果沒有指定路徑,則它只會將當前位置移動到棧中。例如:

PS C:\> Push-Location
PS C:\> Get-Location -Stack
Path
----
C:\

我們現在將指定路徑:

PS C:\> Push-Location C:\Temp\
PS C:\Temp> Get-Location -Stack
Path
----
C:\
C:\

在上面的示例中,當前位置為 **C:\**,因此命令將其推入棧中並移動到該指定的目錄。假設我們將另一個位置推入棧中。

PS C:\Temp> Push-Location C:\Temp\iisadministration\
PS C:\Temp\iisadministration> Get-Location -Stack
Path
----
C:\Temp
C:\
C:\

在上面的示例中,**C:\Temp** 是當前位置,因此它位於棧頂。要跳轉到最後一個位置,我們需要使用 **Pop-Location** 命令。例如:

PS C:\Temp\iisadministration> Pop-Location
PS C:\Temp>

當您執行 **Pop-Location** 命令時,佇列中的最後一個專案(最近的專案)將被刪除。讓我們檢查一下棧。

PS C:\Temp> Get-Location -Stack
Path
----
C:\
C:\

您還可以建立一個新的棧來推入位置,然後您可以使用特定棧中的 **Pop-Location** 命令檢索該位置。例如:

PS C:\Windows\System32> Push-Location WindowsPowerShell -StackName Stack2
PS C:\Windows\System32\WindowsPowerShell> Get-Location -StackName Stack2
Path
----
C:\Windows\System32

在上面的示例中,我們建立了一個名為 **'Stack2'** 的新棧並在其中推入了當前位置,您可以使用特定棧的 **Get-Location** 命令檢視該位置已插入到新棧中。

要從該棧中檢索資料:

PS C:\Windows\System32\WindowsPowerShell> Pop-Location -StackName stack2
PS C:\Windows\System32>

更新於: 2020-11-02

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.