如何在 powershell 脚本中使用属性值

how to use attributes values in powershell script

我在这里使用 Chef 中的 powershell_script 资源在 sqlserver 2012 中创建数据库。

我在脚本中使用了 test1 硬编码的数据库名称。现在我想提供属性文件中的数据库名称。

如何从属性文件获取引用到脚本的值。

powershell_script "create database" do
  code <<-EOH
    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

    $serverName = "localhost"

    $server = new-object ('Microsoft.SqlServer.Management.Smo.Server') $serverName

    #Create a new database
    $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -argumentlist $server, "test1"
    $db.Create()

    #Reference the database and display the date when it was created. 
    $db = $server.Databases["Test_SMO_Database"]
    $db.CreateDate
  EOH
end

尝试使用属性 environment 传递变量(在本例中:dbname),然后在脚本中将其调用为 $dbname

有两种设置属性的方法。

方法一

在attributes/default.rb中,添加这一行

default['yourCookbookNameHere']['dbname'] = 'test1'

在recipes/default.rb

powershell_script "create database" do
  environment ({'dbname' => "#{node['yourCookbookNameHere']['dbname']}"})
  code <<-EOH
    $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -argumentlist $server, $dbname
  EOH
end

方法二

在你的食谱中,像这样将其设置为局部变量

localDbName = 'test1'

powershell_script "create database" do
  environment ({'dbname' => localDbName})
  code <<-EOH
    $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -argumentlist $server, $dbname
  EOH
end

现在修改后的脚本如下所示

powershell_script "create database" do
  code <<-EOH
  [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
  $serverName = "localhost"
  $server = new-object ('Microsoft.SqlServer.Management.Smo.Server') $serverName
  #Create a new database
  $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -argumentlist $server, "#{node['sqlserver']['dbname']}"
  $db.Create()
  EOH
end

Attributes/default.rb

default['sqlserver']['dbname'] = 'testing database'

现在我可以使用属性文件中的值创建数据库。

谢谢你的帮助IsabelHM

花了一点时间弄清楚将 array 定义为节点属性的语法,然后将其成功传递给 powershell_script。显然将其定义为字符串是可行的。

属性:

default['cookbook-name']['attribute-name'] = "'value1', 'value2', 'value3'"

和食谱:

powershell_script 'my script' do
  code <<-EOH
  $array = #{node['cookbook-name']['attribute-name']}
  ...
  EOH
  action :run
  guard_interpreter :powershell_script
  not_if "..."
end

此处使用 powershell_scriptenvironment 属性 的当前答案在它们如何引用代码块中的变量方面是不正确的。 environment 属性 中指定的变量可作为环境变量使用,而不是脚本变量,并且必须作为环境变量引用,如下所示:

powershell_script 'Passed-In Variable Example' do
  environment({ myVar: 'myvalue' })
  code <<-EOH
    Write-Output $env:myVar
  EOH
end

基本上,任何其他使用 environment 属性 将值传递到代码块的答案都是 几乎 正确的,只要确保你在 Powershell 代码中用 $env: 前缀变量名。