繁体   English   中英

将数据传递到Powershell脚本

[英]Pass data to powershell script

我正在使用PowerShell脚本,该脚本需要从文件中获取数据并将它们用作写入其中的函数的参数。 因此,基本上我正在寻找的是JSON或XML文件之类的东西,但是我不确定该使用什么。

我正在寻找的是一种相对易于使用的方法,它传递数据类型或对象而不是字符串。

一部分数据在XML中看起来像这样:

<RegistryEntriesList>
<registryPath>HKLM:\\Software\\Lenovo\\Configuration\\</registryPath> <registryProperty>PATH </registryProperty>
<registryPath>HKLM:\\Software\\Lenovo\\Configuration\\</registryPath> <registryProperty>LOGS </registryProperty>
<registryPath>HKLM:\\Software\\Lenovo\\Connections\\</registryPath> <registryProperty>MinConnectionsPerTarget</registryProperty>
<registryPath>HKLM:\\Software\\Lenovo\\Connections\\</registryPath> <registryProperty>MaxWorkingIscsiConnections</registryProperty>
<registryPath>HKLM:\\Software\\Lenovo\\Connections\\</registryPath> <registryProperty>WaitIntervalInMilliseconds</registryProperty>

另一部分在JSON中会这样:

"entredInput":[{"title":"Powershell","desc":"first"},
      {"title":"json","desc":"third"},
      {"title":"Configfile","desc":"second"}]

还有更多类似的东西。

基本上,我会将这些用于自动化目的。 我知道PowerShell4.0本身具有cmdlet ConvertFrom-JSON,但它在PS2.0上也可以正常工作,我希望我的脚本可以在任何版本的PowerShell(即Windows的任何版本)上运行。 因此,我想XML可能是一个更好的选择,但我不确定。 还有其他选择吗?

我浏览了许多有关JSON和XML的Web链接,它们只是让我很困惑。 请允许我在JSON,XML和SOMETHINGELSE中选择一个更好的选项。 感谢您解决问题。

对于PowerShell 2.0,您可能要使用XML。 对于任何支持JSON的东西,我都会使用它:通常更轻巧。

替代方法是将psd1文件与Import-LocalizedData cmdlet一起使用。 假设您在当前文件夹中创建文件“ Data.psd1”,如下所示:

@{
    RegistryEntriesList = @(
        @{
            registryPath = 'HKLM:\Software\Lenovo\Configuration\'
            registryProperty = 'PATH'
        },
        @{
            registryPath = 'HKLM:\Software\Lenovo\Configuration\'
            registryProperty = 'LOGS'
        }
    )
}

如您所见,它是带有单键RegistryEntriesList的哈希表。 它的值是可用于散列的哈希表的集合。 您可以导入此数据并将其传递给命令,如下所示:

# Our test command...

function New-RegistryEntry {
param (
    [string]$RegistryProperty,
    [string]$RegistryPath
)

    "Got RegistryPath: $RegistryPath and RegistryProperty: $RegistryProperty"
}

Import-LocalizedData -BindingVariable Params -BaseDirectory . -FileName Data.psd1

foreach ($item in $Params.RegistryEntriesList) {
    New-RegistryEntry @item
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM