about_Data_Sections
应用到: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0
在此处插入介绍。
主题
about_Data_Sections
简短说明
说明了数据部分,可使文本字符串和其他只读数据与脚本逻辑隔离。
详细说明
设计用于 Windows PowerShell® 的脚本可以具有一个或多个只包含数据的数据部分。可以在任何脚本、函数或高级函数中包含一个或多个数据部分。数据部分的内容限制为 Windows PowerShell 脚本语言的指定子集。
通过将数据与代码逻辑隔离可以更轻松地识别和管理逻辑和数据。它允许你将单独的字符串资源文件用于文本,例如错误消息和帮助字符串。它还隔离代码逻辑,这有利于安全和验证测试。
在 Windows PowerShell 中,数据部分可用于支持脚本国际化。数据部分可用于更轻松地隔离、查找和处理将要翻译为许多用户界面 (UI) 语言的字符串。
数据部分是 Windows PowerShell 2.0 功能。带有数据部分的脚本不会在 Windows PowerShell 1.0 未修订版本中运行。
语法
数据部分的语法如下所示:
DATA [-supportedCommand <cmdlet-name>] {
<Permitted content>
}
Data 关键字是必需的。不区分大小写。
允许的内容仅限于以下元素:
- All Windows PowerShell operators, except -match
- If, Else, and ElseIf statements
- The following automatic variables: $PsCulture, $PsUICulture, $True,
$False, and $Null
- Comments
- Pipelines
- Statements separated by semicolons (;)
- Literals, such as the following:
a
1
1,2,3
"Windows PowerShell 2.0"
@( "red", "green", "blue" )
@{ a = 0x1; b = "great"; c ="script" }
[XML] @'
<p> Hello, World </p>
'@
- Cmdlets that are permitted in a Data section. By default, only the
ConvertFrom-StringData cmdlet is permitted.
- Cmdlets that you permit in a Data section by using the
SupportedCommand parameter.
当在数据部分中使用 ConvertFrom-StringData cmdlet 时,可以将键/值对放置于带单引号或双引号的字符串中,或者将其放置于带单引号或双引号的 here-string 中。但是,包含变量和子表达式的字符串必须放置于带单引号的字符串中或带单引号的 here-string 中,以便不会展开变量并且子表达式不可执行。
SUPPORTEDCOMMAND
借助 SupportedCommand 参数,你可以指示 cmdlet 或函数仅生成数据。它旨在允许用户在他们编写或测试的数据部分中包含 cmdlet 和函数。
SupportedCommand 的值是以逗号分隔的一个或多个 cmdlet 或函数名称的列表。
例如,以下数据部分包含用户编写的且可格式化 XML 文件中的数据的 Format-XML cmdlet:
DATA -supportedCommand Format-XML
{
Format-XML -strings string1, string2, string3
}
使用数据部分
若要使用数据部分的内容,请将其分配给变量并使用变量表示法访问该内容。
例如,以下数据部分包含将 here-string 转换为哈希表的 ConvertFrom-StringData 命令。该哈希表将分配给 $TextMsgs 变量。
$TextMsgs 变量不属于数据部分。
$TextMsgs = DATA {
ConvertFrom-StringData -stringdata @'
Text001 = Windows 7
Text002 = Windows Server 2008 R2
'@
}
若要访问 $TextMsgs 的哈希表中的键和值,请使用以下命令。
$TextMsgs.Text001
$TextMsgs.Text002
示例
简单的数据字符串。
DATA {
"Thank you for using my Windows 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".
"@
}
包含用户编写的且可生成数据的 cmdlet 的数据部分:
DATA -supportedCommand Format-XML {
Format-XML -strings string1, string2, string3
}
另请参阅
about_Automatic_Variables
about_Comparison_Operators
about_Hash_Tables
about_If
about_Operators
about_Quoting_Rules
about_Script_Internationalization
ConvertFrom-StringData
Import-LocalizedData