自從上手 Git、PowerShell、.NET Core/.NET 6 之後,我愈來愈喜歡用 Cmder/Terminal 下指令取代滑滑鼠,兩隻手留在鍵盤上操作,比伸手去拿滑鼠、眼睛定位更有效率,也算趕上這幾年 CLI 復興的時代潮流。

以統計資料夾佔用空間為例,前陣子學到在 Windows 要做小範圍統計,可以用 GNU du、SysInternals du,比 WinDirStat 簡便快速,甚且還能輸出 CSV 串接 PowerShell 做出進階應用,十分方便。

不過,今天發現一個小問題 - 當想對目錄進行反覆操作,一般會先 CD (Change Directory) 切換到該目錄下,但 CD 不支援 UNC \\server-name\share-name\dir-name,會得到 CMD does not support UNC paths as current directories 錯誤訊息。原以為無解,意外找到一個小密技 - pushd 可以先記下目前所在目錄再切到新目錄,稍後 popd 時再切回原本的目錄,而它有個較少人知道的方便功能:

If you specify a network path, the pushd command temporarily assigns the highest unused drive letter (starting with Z:) to the specified network resource. The command then changes the current drive and directory to the specified directory on the newly assigned drive. If you use the popd command with command extensions enabled, the popd command removes the drive-letter assignment created by pushd. 當 pushd UNC 時,pushd 指令會由 Z 開始往前找到第一個未使用的磁碟機代號,將 UNC 對映成網路磁碟機並將目錄切換過去,popd 時再移除網路磁碟機並回到原先的目錄。

直接看示範:

一開始在 X:,cd UNC 路徑失敗,pushd UNC 路徑後切到 Z:,Z: 即為 UNC 路徑內容,之後 popd 回到 X:,Z: 也消失。

再學一招。

[2022-02-25 補充] PowerShell 支援切換到 UNC。(感謝讀者 JR 分享)


Comments

# by JR

PowerShell 就可以直接切換了

# by Jeffrey

to JR, 謝謝分享,已補充於本文。

# by jerry0512

補充一下。如果這個路徑經常要使用,可以先用net use 給它一個虛擬磁碟機: net use Z: \\jeffwin10\dosbox z: dir /od rem ... 其他操作... 最後移除 Z: net use Z: /delete

Post a comment