PowerShell管理文件和文件夾

(一)查詢

使用 Get-ChildItem 直接獲取某個文件夾中的所有項目。 添加可選的 Force 參數以顯示隱藏項或系統項。爲了顯示包含的項,你還需要指定 -Recurse 參數。 (這可能需要相當長的時間才能完成。)

Get-ChildItem -Path C:\ -Force
Get-ChildItem -Path C:\ -Force -Recurse

Get-ChildItem 可以使用其 Path、Filter、Include 和 Exclude 參數篩選項,但那些通常只基於名稱。 還可以通過使用 Where-Object 基於項的其他屬性執行復雜的篩選。

Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object -FilterScript {($_.LastWriteTime -gt '2005-10-01') -and ($_.Length -ge 1mb) -and ($_.Length -le 10mb)}

還可以使用通配符匹配進行枚舉,Windows PowerShell 通配符表示法包括:

星號 (*) 匹配零個或多個出現的任何字符。
問號 (?) 完全匹配一個字符。
左括號 ([) 字符和右括號 (]) 字符括起一組要匹配的字符。

若要在 Windows 目錄中查找帶有後綴 .log 並且基名稱中正好有五個字符的所有文件,請輸入以下命令:

Get-ChildItem -Path C:\Windows\?????.log

若要在 Windows 目錄中查找以字母 x 開頭的所有文件,請鍵入:

Get-ChildItem -Path C:\Windows\x*

若要查找名稱以 x 或 z 開頭的所有文件,請鍵入:

Get-ChildItem -Path C:\Windows\[xz]*

也可以使用排除參數,例如排除名稱包含9516的文件:

Get-ChildItem -Path C:\WINDOWS\System32\w*32*.dll -Exclude *[9516]*
Get-ChildItem -Path C:\Windows\*.dll -Recurse -Exclude [a-y]*.dll

包含參數和排除參數可結合使用:

Get-ChildItem -Path C:\Windows -Include *.dll -Recurse -Exclude [a-y]*.dll

(二)複製

如果目標文件或文件夾已存在,則複製嘗試失敗。 若要覆蓋預先存在的目標,請使用 Force 參數。即使當目標爲只讀時,該命令也有效。

Copy-Item -Path C:\boot.ini -Destination C:\boot.bak -Force

你仍然可以使用其他工具執行文件系統複製。 XCOPY、ROBOCOPY 和 COM 對象(如 Scripting.FileSystemObject)都適用於 Windows PowerShell。 例如,可以使用 Windows Script Host Scripting.FileSystem COM 類將 C:\boot.ini 備份到 C:\boot.bak:

(New-Object -ComObject Scripting.FileSystemObject).CopyFile('C:\boot.ini', 'C:\boot.bak')

(三)創建

如果某個 Windows PowerShell 提供程序具有多個類型的項(例如,用於區分目錄和文件的 FileSystem Windows PowerShell 提供程序),則需要指定項類型。

New-Item -Path 'C:\temp\New Folder' -ItemType Directory
New-Item -Path 'C:\temp\New Folder\file.txt' -ItemType File

(四)刪除

刪除的 時候,如果不希望系統針對每個包含的項都提示你,則指定 Recurse 參數:

Remove-Item -Path C:\temp\DeleteMe -Recurse

您也可以關注下方微信公衆號獲取更多資訊
PowerShell管理文件和文件夾

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章