第 4 章

常用指令入門:檔案、資料夾、路徑操作

本章重點

  • 學會用 Set-Location 切換路徑
  • Get-ChildItem 列出檔案
  • New-Item 建立檔案與資料夾
  • 理解絕對路徑與相對路徑的差別

路徑觀念

在 PowerShell 裡操作檔案,一定要先搞清楚「你在哪裡」。

  • 絕對路徑:從根目錄開始的完整路徑,例如 C:\Users\Jack\Documents
  • 相對路徑:從目前位置出發的路徑,例如 .\Documents..\Desktop
# . 代表目前資料夾
# .. 代表上一層資料夾
# ~ 代表家目錄(C:\Users\你的帳號)

Set-Location ~
Set-Location .\Documents
Set-Location ..\Desktop

切換資料夾:Set-Location

# 切換到 C 槽根目錄
Set-Location C:\

# 切換到桌面
Set-Location ~\Desktop

# 回到上一層
Set-Location ..

# 回到家目錄
Set-Location ~

# 查看目前所在路徑
Get-Location
別名:Set-Location 可以寫成 cdGet-Location 可以寫成 pwd。 和 Linux/cmd 的操作習慣一樣。

列出內容:Get-ChildItem

# 列出目前資料夾所有內容
Get-ChildItem

# 列出特定資料夾
Get-ChildItem C:\Users

# 只列出 .txt 檔
Get-ChildItem -Filter "*.txt"

# 列出包含隱藏檔
Get-ChildItem -Force

# 遞迴列出所有子資料夾的內容
Get-ChildItem -Recurse

# 只顯示名稱
Get-ChildItem | Select-Object Name

建立檔案與資料夾:New-Item

# 建立新資料夾
New-Item -Path "C:\test-folder" -ItemType Directory

# 建立新檔案
New-Item -Path "C:\test-folder\hello.txt" -ItemType File

# 建立檔案並寫入內容
New-Item -Path ".\note.txt" -ItemType File -Value "這是內容"
簡寫: -ItemType Directory 可以寫成 -Type Directory, 建資料夾的常見縮寫是 mkdir 資料夾名稱(別名)。

查看路徑是否存在

# 回傳 True 或 False
Test-Path "C:\Windows"

# 在腳本裡常這樣用
if (Test-Path "C:\mydata") {
    Write-Output "資料夾存在"
} else {
    Write-Output "資料夾不存在"
}
常見錯誤: 路徑中有空格時,記得用引號括起來:Set-Location "C:\Program Files"。 沒有引號的話 PowerShell 會把空格後面的字當作另一個參數。
小練習:
  1. 切換到桌面:Set-Location ~\Desktop
  2. 列出桌面所有檔案:Get-ChildItem
  3. 在桌面建立一個測試資料夾:New-Item -Path ".\test123" -ItemType Directory
  4. 進入那個資料夾:Set-Location .\test123
  5. 確認路徑:Get-Location

小結

Set-LocationGet-ChildItemNew-Item 是最基本的三個操作指令。 搞清楚絕對路徑與相對路徑,是後面所有操作的基礎。

下一章,學會複製、搬移、刪除與查看檔案內容。