about_Data_Sections

简短说明

介绍 data 部分,这些节将文本字符串和其他只读数据与脚本逻辑隔离开来。

长说明

专为 PowerShell 设计的脚本可以有一个或多个仅包含数据的 data 部分。 可以在任何脚本、函数或高级函数中包含一个或多个 data 节。 data 节的内容仅限于 PowerShell 脚本语言的指定子集。

将数据与代码逻辑分离可以更轻松地识别和管理逻辑和数据。 它允许你为文本(例如错误消息和帮助字符串)使用单独的字符串资源文件。 它还隔离了代码逻辑,这有利于安全和验证测试。

在 PowerShell 中,可以使用 data 部分来支持脚本国际化。 可以使用 data 节更轻松地隔离、查找和处理可翻译成其他语言的字符串。

PowerShell 2.0 功能中添加了 data 部分。

语法

data 节的语法如下所示:

data [<variable-name>] [-SupportedCommand <cmdlet-name>] {
    <Permitted content>
}

需要 data 关键字。 它不区分大小写。 允许的内容仅限于以下元素:

  • -match 之外的所有 PowerShell 运算符

  • ifelseelseif 语句

  • 以下自动变量:$PSCulture$PSUICulture$true$false$null

  • 注释

  • 管道

  • 用分号 (;) 分隔的语句

  • 文本,例如:

    a
    1
    1,2,3
    "PowerShell 2.0"
    @( "red", "green", "blue" )
    @{ a = 0x1; b = "great"; c ="script" }
    [xml] @'
    <p> Hello, World </p>
    '@
    
  • data 节中允许的 Cmdlet。 默认情况下,仅允许使用 ConvertFrom-StringData cmdlet。

  • 使用 data 参数在 -SupportedCommand 节中允许的 Cmdlet。

ConvertFrom-StringData 节中使用 data cmdlet 时,可以将键值对括在单引号或双引号字符串中,或用单引号或双引号的此处字符串括起来。 但是,包含变量和子表达式的字符串必须括在单引号字符串或单引号的此处字符串中,以便不会扩展变量,并且子表达式不是可执行的。

-SupportedCommand

SupportedCommand 参数允许你指示 cmdlet 或函数仅生成数据。 它旨在允许用户在已编写或测试的 data 节中包含 cmdlet 和函数。

SupportedCommand 的值是一个或多个 cmdlet 或函数名称的逗号分隔列表。

例如,以下 data 部分包括一个用户编写的 cmdlet Format-Xml,用于格式化 XML 文件中的数据:

data -SupportedCommand Format-Xml
{
    Format-Xml -Strings string1, string2, string3
}

使用 data

若要使用 data 节的内容,请将其分配给变量,并使用变量表示法访问内容。

例如,以下 data 节包含将此处字符串转换为哈希表的 ConvertFrom-StringData 命令。 哈希表将被赋给 $TextMsgs 变量。

$TextMsgs 变量不是 data 节的一部分。

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

若要访问 $TextMsgs 中哈希表内的键和值,请使用以下命令。

$TextMsgs.Text001
$TextMsgs.Text002

或者,可以将变量名称放在 data 节的定义中。 例如:

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-string:

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

使用 ConvertFrom-StringData cmdlet 的带双引号的 here-string:

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

一个 Data 节,其中包含用户编写的用于生成数据的 cmdlet:

data -SupportedCommand Format-Xml {
    Format-Xml -Strings string1, string2, string3
}

另请参阅