在 PowerShell 中使用 .NET 框架建立檔案選擇視窗,讓使用者以圖形介面選擇檔案。
若要在 PowerShell 中使用檔案選擇視窗,必須透過 .NET 框架的 OpenFileDialog 來建立視窗,比較方便的做法是以自訂函數的方式,將建立視窗的程式碼包裝起來:
# 自訂檔案選擇視窗函數 Function Get-FileName($initialDirectory) { # 以 .NET 框架建立檔案選擇視窗 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog # 設定初始目錄 $OpenFileDialog.initialDirectory = $initialDirectory # 設定篩選器為 CSV 檔、所有檔案 $OpenFileDialog.filter = "CSV Files(*.csv)|*.csv|All Files|*.*" # 顯示視窗 $OpenFileDialog.ShowDialog() | Out-Null # 傳回選擇的檔案名稱 $OpenFileDialog.filename }
建立好 Get-FileName 這個自訂的檔案選擇視窗函數之後,使用方式很簡單,只要呼叫它加上初始的目錄即可:
# 使用檔案選擇視窗選擇檔案 $InputFile = Get-FileName "D:" # 顯示檔案名稱 $InputFile
開啟的檔案視窗會像這樣,使用者可以很方便的選擇檔案:
取得檔案名稱之後,若要讀取檔案內容,可以使用 Get-Content 指令:
# 讀取檔案內容 $InputData = Get-Content $InputFile # 輸出檔案內容 $InputData
若要日使用者選擇目錄的話,可以改用 .NET 框架的 FolderBrowserDialog 類別,以下是一個簡單的範例:
# 自訂目錄選擇視窗函數 Function Get-FolderName1() { # 以 .NET 框架建立目錄選擇視窗 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null $OpenFolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog # 設定說明文字 $OpenFolderDialog.Description = "選擇目錄示範 by Office 指南" # 顯示視窗 $OpenFolderDialog.ShowDialog() | Out-Null # 傳回選擇的檔案名稱 $OpenFolderDialog.SelectedPath }
呼叫 Get-FolderName1 這個自訂的函數,即可讓使用者選擇目錄:
# 使用目錄選擇視窗選擇目錄 $Folder = Get-FolderName1 # 顯示目錄名稱 $Folder
開啟的目錄選擇視窗會像這樣:
FolderBrowserDialog 在開啟視窗時,預設會以「桌面」為最上層的根目錄,讓使用者選擇「桌面」上的目錄,如果想讓使用者選擇電腦中其他位置的目錄,可以透過 RootFolder 屬性改變其根目錄。另外若要設定預設選擇的目錄,則可使用 SelectedPath 屬性來指定。
# 自訂目錄選擇視窗函數 Function Get-FolderName2($SelectedPath) { [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null $OpenFolderDialog = New-Object System.Windows.Forms.FolderBrowserDialog $OpenFolderDialog.Description = "選擇目錄示範 by Office 指南" # 設定根目錄為「本機」 $OpenFolderDialog.RootFolder = "MyComputer" # 設定預設選擇的目錄 $OpenFolderDialog.SelectedPath = $SelectedPath $OpenFolderDialog.ShowDialog() | Out-Null $OpenFolderDialog.SelectedPath }
這裡我們將根目錄設定為「本機」,這樣即可讓使用者選擇電腦中任意位置的目錄,而執行時還可以透過 SelectedPath 參數設定預設的目錄:
# 使用目錄選擇視窗選擇目錄 $Folder = Get-FolderName2 "D:MyFolder" # 顯示目錄名稱 $Folder
執行後開啟的視窗會像這樣:
RootFolder 在設定時只能使用幾種它支援的路徑選項,不能自己指定任意的路徑,例如這裡使用的 MyComputer 就是代表「本機」。以下是可用的路徑選項:Desktop、Programs、MyDocuments、Personal、Favorites、Startup、Recent、SendTo、StartMenu、MyMusic、MyVideos、DesktopDirectory、MyComputer、NetworkShortcuts、Fonts、Templates、CommonStartMenu、CommonPrograms、CommonStartup、CommonDesktopDirectory、ApplicationData、PrinterShortcuts、LocalApplicationData、InternetCache、Cookies、History、CommonApplicationData、Windows、System、ProgramFiles、MyPictures、UserProfile、SystemX86、ProgramFilesX86、CommonProgramFiles、CommonProgramFilesX86、CommonTemplates、CommonDocuments、CommonAdminTools、AdminTools、CommonMusic、CommonPictures、CommonVideos、Resources、LocalizedResources、CommonOemLinks、CDBurning。