當您新增別名、函數和變數時,其實只是將它們加入到目前的 Windows PowerShell 工作階段。若是結束該工作階段或是關閉 Windows PowerShell,這些變更就會遺失。

若要保留這些變更,您可以建立 Windows PowerShell 設定檔,然後將那些別名、函數和變數加入到設定檔中。此設定檔會在每次啟動 Windows PowerShell 時載入。

為了載入設定檔,您的 Windows PowerShell 執行原則必須允許您載入組態檔。如果未能載入,嘗試載入設定檔會失敗,而且 Windows PowerShell 會顯示錯誤訊息。

認識設定檔

您可以在 Windows PowerShell 中設定 4 個不同的設定檔。這些設定檔會依載入順序列出。在套用情況下,最特定設定檔的優先順序高於較不特定的設定檔。

  • %windir%\system32\WindowsPowerShell\v1.0\profile.ps1

    這個特定檔會套用到所有使用者和所有殼層。

  • %windir%\system32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1

    這個設定檔會套用到所有使用者,但是僅會套用到 Microsoft.PowerShell 殼層。

  • %UserProfile%\My Documents\WindowsPowerShell\profile.ps1

    這個設定檔僅會套用到目前使用者,但是會影響到所有的殼層。

  • %UserProfile%\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

    這個設定檔僅會套用到目前使用者和 Microsoft.PowerShell 殼層。

建立設定檔

當您建立或匯入變數、別名或函數或是新增 Windows PowerShell 嵌入式管理單元時,這些項目只會加入到目前的工作階段。若是結束該工作階段或是關閉視窗,則這些項目就會遺失。

若要儲存您經常使用的變數、別名、函數與命令並且希望可以在每一個 Windows PowerShell 工作階段中使用這些項目,請將它們加入到 Windows PowerShell 設定檔中。

也可以建立、共用和散佈設定檔,以便在較大型企業中強制使用一致的 Windows PowerShell 檢視。

Windows PowerShell 設定檔不會自動建立。若要建立設定檔,請在指定位置建立包含指定名稱的文字檔案。基本上,您會使用使用者特定、殼層特定的設定檔,即一般所指的 Windows PowerShell 使用者設定檔。這個設定檔的位置會存放於 $profile 變數。

若要顯示 Windows PowerShell 設定檔的路徑,請輸入:

$profile

若要判斷是否已經在系統上建立 Windows PowerShell 設定檔,請輸入:

test-path $profile

如果系統上已經有設定檔,回應會是 True,否則為 False

若要建立 Windows PowerShell 設定檔檔案,請輸入:

new-item -path $profile -itemtype file -force

若要在 [記事本] 中開啟設定檔,請輸入:

notepad $profile

若要建立像是套用到所有使用者和所有殼層的其他設定檔,請輸入:

new-item -path $env:windir\System32\WindowsPowerShell\v1.0\profile.ps1 -itemtype file -force

只有在檔案已確實位於該路徑且設定檔具有儲存於 $profile 變數中的檔名時,設定檔才能發揮作用。因此,如果以 [記事本] 建立設定檔然後儲存,或者如果將設定檔複製到系統上,請務必將檔案儲存在適當路徑並且以 $profile 變數指定的檔案儲存設定檔。

若是以 [記事本] 建立設定檔,請使用引號括住檔名以保存 PS1 的副檔名。例如:

"Microsoft.PowerShell_profile.ps1"

如果沒有使用引號,[記事本] 會為這個檔案加上 .txt 副檔名,進而導致 Windows PowerShell 無法成功辨識。

請使用此設定檔來儲存經常使用的別名、函數和變數。還有一個相當實用的函數,可以利用您偏好的文字編輯器開啟使用者設定檔。例如,下列命令會建立名為 pro 且會以 [記事本] 開啟使用者設定檔的函數。

function pro { notepad $profile }

設計良好的設定檔甚至可以讓 Windows PowerShell 的使用更簡單,還可以用來管理系統。




目錄