about_Variables

適用於: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0, Windows PowerShell 5.0

主題

about_Variables

簡短描述

描述變數如何儲存可用於 Windows PowerShell® 中的值。

詳細描述

您可以用 Windows PowerShell 變數儲存所有類型的值。這類變數通常用來儲存命令結果,以及儲存命令和運算式中所用的元素,例如名稱、路徑、設定和值。

變數是用以儲存值的一個記憶體單位。在 Windows PowerShell 中,變數是以貨幣符號 ($) 開頭的文字字串 (如 $a、$process 或 $my_var) 表示。

變數名稱不區分大小寫。變數名稱可以包含空格和特殊字元,但這些都難以使用,應加以避免。

Windows PowerShell 中有數個不同類型的變數。

使用者建立的變數:

使用者建立的變數是由使用者建立和維護。根據預設,只有當 Windows PowerShell 視窗為開啟狀態時,您在 Windows PowerShell 命令列建立的變數才會存在,而當您關閉此視窗時即會遺失。若要儲存變數,請將它加入至您的 Windows PowerShell 設定檔。您也可以用具有全域、指令碼或本機範圍的指令碼建立變數。

自動變數:

自動變數可儲存 Windows PowerShell 的狀態。這些變數是由 Windows PowerShell 建立,而 Windows PowerShell 會視需要變更其值以維護其精確度。使用者無法變更這些變數的值。例如,$PSHome 變數會儲存 Windows PowerShell 安裝目錄的路徑。

如需自動變數的詳細資訊、清單和描述,請參閱 about_Automatic_Variables。

喜好設定變數:

喜好設定變數會儲存 Windows PowerShell 的使用者喜好設定。這些變數是由 Windows PowerShell 建立,而且會填入預設值。使用者可以變更這些變數的值。例如,$MaximumHistoryCount 變數可決定工作階段歷程記錄中的項目數上限。

如需喜好設定變數的詳細資訊、清單和描述,請參閱 about_Preference_Variables。

使用變數

若要建立新變數,請使用指派陳述式來指派值給變數。在使用此變數前,您不須加以宣告。所有變數的預設值都是 $null。

例如:

        PS> $MyVariable = 1, 2, 3
        PS> $path = "C:\Windows\System32"

變數非常適合於儲存命令的結果。

例如:

          
        PS> $processes = Get-Process         
     
        PS> $Today = (Get-Date).date

若要顯示變數的值,請輸入變數名稱,前面加上貨幣符號 ($)。

例如:

        PS> $MyVariable
        1
        2
        3
        PS> $Today
        Thursday, September 03, 2009 12:00:00 AM

若要變更變數的值,請指派新值給變數。

下列範例顯示 $MyVariable 變數的值、變更此變數的值,然後顯示新值。

        PS> $MyVariable
        1
        2
        3
        PS> $MyVariable = "The green cat."
        PS> $MyVariable
        The green cat.

若要刪除變數的值,請使用 Clear-Variable Cmdlet 或將值變更為 $null。

        PS> Clear-Variable -name MyVariable  

        -or-

        PS> $MyVariable = $null

若要刪除變數,請使用 Remove-Variable 或 Remove-Item Cmdlet。(在本主題稍後會討論這些 Cmdlet)。

       PS> remove-variable -name MyVariable

       PS> remove-item -path variable:\myvariable

若要取得 Windows PowerShell 工作階段中的所有變數清單,請輸入:

       get-variable

變數類型

您可以在變數中儲存任何類型的物件,包括整數、字串、陣列、雜湊資料表,以及代表處理程序、服務、事件記錄檔和電腦的物件。

Windows PowerShell 變數為「鬆散型別」,這表示它們不限於特定類型的物件。單一變數甚至可以同時包含不同類型的物件集合 (「陣列」)。

變數的資料類型 (.NET Framework 類型) 取決於變數值的 .NET 類型。

例如:

        PS> $a = 12     (System.Int32)
        
        PS> $a = "Word" (System.String)

        PS> $a = 12, "Word" (System.Int32, System.String)

        PS> $a = dir C:\Windows\System32  (Files and folders)

您可以使用類型屬性和轉型標記法來確保變數只能包含指定類型的物件或可以轉換為該類型的物件。如果您嘗試指派另一種類型的值,Windows PowerShell 會嘗試將此值轉換成它的類型。如果無法這麼做,指派陳述式會失敗。

若要使用轉型標記法,請在變數名稱之前 (在指派陳述式的左邊) 輸入類型名稱 (以括號括住)。下列範例會建立只能包含整數的 $number 變數、只能包含字串的 $words 變數,以及只能包含 DateTime 物件的 $dates 變數。

        PS> [int]$number = 8
        PS> $a = "12345" (The string is converted to an integer.)
        PS> $a = "Hello"
        Cannot convert value "Hello" to type "System.Int32". Error: "Input string was not in a correct format."
        At line:1 char:3
        + $a <<<<  = "Hello"
            + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
            + FullyQualifiedErrorId : RuntimeException
        PS> [string]$words = "Hello"

        PS> $words = 2   (The integer is converted to a string.)

        PS> $words + 10  (The strings are concatenated.)
        210              
        PS> [datetime] $dates = "09/12/91" (The string is converted to a DateTime object.)

        PS> $dates
        Thursday, September 12, 1991 12:00:00 AM

        PS> $dates = 10  (The integer is converted to a DateTime object.)
        PS> $dates
        Monday, January 01, 0001 12:00:00 AM
                

在命令與運算式中使用變數

若要在命令或運算式中使用變數,請輸入變數名稱,前面加上貨幣符號 ($)。

如果變數名稱 (和貨幣符號) 沒有括在引號內或是括在雙引號 (") 內,此變數的值就會使用於命令或運算式中。

如果變數名稱 (和貨幣符號) 括在單引號 (') 內,則變數名稱會使用於運算式中。

例如,第一個命令會取得 $profile 變數的值,這是 Windows PowerShell 主控台中 Windows PowerShell 使用者設定檔的路徑。第二個命令會在 [記事本] 中開啟此檔案,而第三個和第四個命令會在運算式中使用此變數的名稱。

        PS> $profile
        C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
        PS> notepad $profile 
        - or -
        PS> notepad "$profile"
        C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
        PS> '$profile'
        $profile
        PS> 'Use the $profile variable.'
        Use the $profile variable.

如需在 Windows PowerShell 中使用引號的詳細資訊,請參閱 about_Quoting_Rules。

包含特殊字元的變數名稱

變數名稱以貨幣符號開頭。它們可以包含英數字元和特殊字元。變數名稱的長度僅受限於可用的記憶體。

可能的話,變數名稱應該只包含英數字元和底線字元 (_)。包含空格和其他特殊字元的變數名稱難以使用,應加以避免。

若要建立或顯示包含空格或特殊字元的變數名稱,請以大括號括住變數名稱。這會引導 Windows PowerShell 逐字解譯變數名稱中的字元。

例如,下列命令會建立並接著顯示名為 "save-items" 的變數。

          C:\PS> ${save-items} = "a", "b", "c"
          C:\PS> ${save-items}
          a
          b
          c

下列命令可取得以 "ProgramFiles(x86)" 環境變數表示的目錄中的子項目。

          C:\PS> Get-childitem ${env:ProgramFiles(x86)}

若要參考包含大括號的變數名稱,請以大括號括住變數名稱,並使用倒單引號 (逸出) 字元來逸出大括號。例如,若要建立名為 "this{value}is" 且值為 1 的變數,請輸入:

          C:\PS> ${this`{value`}is} = 1
          C:\PS> ${this`{value`}is}
          1

變數和範圍

根據預設,變數只適用於其建立所在的範圍。

例如,您在函式中建立的變數只適用於該函式。您在指令碼中建立的變數只適用於該指令碼 (除非您將此指令碼進行 dot-source 處理,以將它加入至目前的範圍)。

您可以使用範圍修飾詞來變更變數的預設範圍。下列運算式會建立名為 "Computers" 的變數。即使此變數建立於指令碼或函式中,仍具有全域範圍。

            $global:computers = "Server01"

如需詳細資訊,請參閱 about_Scopes。

儲存變數

您建立的變數只適用於您建立它們的工作階段中。當您關閉您的工作階段,這些變數就會遺失。

若要在您啟動的每個 Windows PowerShell 工作階段中建立變數,請將該變數加入至您的 Windows PowerShell 設定檔。

例如,若要在每個 Windows PowerShell 工作階段中變更 $VerbosePreference 變數的值,請將下列命令加入至您的 Windows PowerShell 設定檔。

  $VerbosePreference = "Continue"

您可以在文字編輯器 (如 [記事本]) 中開啟您的設定檔,以將此命令加入至設定檔。如需 Windows PowerShell 設定檔的詳細資訊,請參閱 about_profiles。

變數:磁碟機

Windows PowerShell 變數提供者會建立一個變數:外觀和作用類似檔案系統磁碟機的磁碟機,但是它包含您工作階段中的變數與其值。

若要變更為 variable:請輸入:

        set-location variable:
        
         (or "cd variable:")

若要列出 Variable:磁碟機中的項目 (變數),請使用 Get-Item 或 Get-ChildItem Cmdlet。例如:

         get-childitem variable:
         (or "dir" or "ls")

若要取得特定變數的值,請使用檔案系統標記法來指定磁碟機的名稱和變數的名稱。例如,若要取得 $PSCulture 自動變數,請使用下列命令。

         get-item variable:\PSCulture      

         Name                           Value
         ----                           -----
         PSCulture                      en-US        

如需 Variable:磁碟機和 Windows PowerShell 變數提供者的詳細資訊,請輸入 "get-help variable"。

變數 CMDLET

Windows PowerShell 包含一組設計用來管理變數的 Cmdlet。

         Cmdlet Name           Description
         -----------           -----------

         Clear-Variable        Deletes the value of a variable.
         Get-Variable          Gets the variables in the current console.
         New-Variable          Creates a new variable.
         Remove-Variable       Deletes a variable and its value.
         Set-Variable          Changes the value of a variable.

若要取得這些 Cmdlet 的說明,請輸入:"Get-Help <cmdlet-hame>"。

另請參閱

about_Automatic_Variables

about_Environment_Variables

about_Preference_Variables

about_Profiles

about_Quoting_Rules

about_Scopes