about_Data_Sections

簡短描述

說明數據區段,這些區段會隔離文字字串和其他只讀數據與腳本邏輯。

詳細描述

專為 PowerShell 設計的腳本可以有一或多個只包含數據的 Data 區段。 您可以在任何文稿、函式或進階函式中包含一或多個數據區段。 Data 區段的內容僅限於 PowerShell 腳本語言的指定子集。

將數據與程式代碼邏輯分開,可讓您更輕鬆地識別和管理邏輯和數據。 它可讓您針對文字有個別的字串資源檔,例如錯誤訊息和說明字串。 它也會隔離程式代碼邏輯,以利安全性和驗證測試。

在 PowerShell 中,[數據] 區段用來支援腳本國際化。 您可以使用 [數據] 區段,更輕鬆地隔離、尋找及處理將轉譯成許多使用者介面 (UI) 語言的字串。

[數據] 區段是 PowerShell 2.0 功能。 具有數據區段的腳本將不會在沒有修訂的情況下在 PowerShell 1.0 中執行。

語法

Data 區段的語法如下所示:

DATA [<variable-name>] [-supportedCommand <cmdlet-name>] {
    <Permitted content>
}

需要 Data 關鍵詞。 不區分大小寫。 允許的內容僅限於下列元素:

  • 所有 PowerShell 運算子,但除外 -match

  • IfElseElseIf 陳述式

  • 下列自動變數:$PsCulture、、、$PsUICulture$True$False$Null

  • 註解

  • Pipelines

  • 以分號分隔的語句 (;

  • 常值,例如:

    a
    1
    1,2,3
    "PowerShell 2.0"
    @( "red", "green", "blue" )
    @{ a = 0x1; b = "great"; c ="script" }
    [XML] @'
    <p> Hello, World </p>
    '@
    
  • Data 區段中允許的 Cmdlet。 根據預設,只允許 Cmdlet ConvertFrom-StringData

  • 您可以使用 參數,在 Data 區段中允許的 -SupportedCommand Cmdlet。

當您在 Data 區段中使用 ConvertFrom-StringData Cmdlet 時,可以將索引鍵/值組括在單引號或雙引號字串中,或以單引號或雙引弧括住 here-strings。 不過,包含變數和子表達式的字串必須以單引號字串或以單引弧括住此處的字串,讓變數不會展開,而且子表達式不是可執行的。

-SupportedCommand

參數 -SupportedCommand 可讓您指出 Cmdlet 或函式只會產生數據。 其設計目的是允許使用者在已撰寫或測試的數據區段中包含 Cmdlet 和函式。

的值 -SupportedCommand 是一或多個 Cmdlet 或函式名稱的逗號分隔清單。

例如,下列數據區段包含使用者寫入的 Cmdlet, Format-Xml可格式化 XML 檔案中的數據:

DATA -supportedCommand Format-Xml
{
    Format-Xml -Strings string1, string2, string3
}

使用數據區段

若要使用 Data 區段的內容,請將它指派給變數,並使用變數表示法來存取內容。

例如,下列數據區段包含 ConvertFrom-StringData 將 here-string 轉換成哈希表的命令。 哈希表會指派給 $TextMsgs 變數。

變數 $TextMsgs 不是數據區段的一部分。

$TextMsgs = DATA {
    ConvertFrom-StringData -StringData @'
Text001 = Windows 7
Text002 = Windows Server 2008 R2
'@
}

若要存取 中 $TextMsgs哈希表中的索引鍵和值,請使用下列命令。

$TextMsgs.Text001
$TextMsgs.Text002

或者,您可以將變數名稱放在 [資料] 區段的定義中。 例如:

DATA TextMsgs {
    ConvertFrom-StringData -StringData @'
Text001 = Windows 7
Text002 = Windows Server 2008 R2
'@
}

$TextMsgs

結果與上一個範例相同。

Name                           Value
----                           -----
Text001                        Windows 7
Text002                        Windows Server 2008 R2

範例

簡單數據字串。

DATA {
    "Thank you for using my PowerShell Organize.pst script."
    "It is provided free of charge to the community."
    "I appreciate your comments and feedback."
}

包含允許變數的字串。

DATA {
    if ($null) {
        "To get help for this cmdlet, type get-help new-dictionary."
    }
}

使用 ConvertFrom-StringData Cmdlet 的單引號 here 字串:

DATA {
    ConvertFrom-StringData -stringdata @'
Text001 = Windows 7
Text002 = Windows Server 2008 R2
'@
}

使用 ConvertFrom-StringData Cmdlet 的雙引號 here 字串:

DATA  {
    ConvertFrom-StringData -stringdata @"
Msg1 = To start, press any key.
Msg2 = To exit, type "quit".
"@
}

資料區段,其中包含產生資料的使用者寫入 Cmdlet:

DATA -supportedCommand Format-XML {
    Format-Xml -strings string1, string2, string3
}

另請參閱