具有Packer(.json)输入参数的PowerShell脚本

时间:2018-11-23 10:43:22

标签: powershell

我有这个Ps1脚本,

param   ([string] $userpassword, [string] $UserName)

Write-host "Start.." (Get-date)

Write-host "User Name is "$UserName Write-host "User password is
"$userpassword

if ($userpassword.length -lt 0) {
    Write-host "Please enter password!"$UserName }

Write-host "End.." (Get-date)

packer(.json)如下:

"provisioners":    [
    {
      "type": "powershell",
      "environment_vars": 
      [
        "userpassword=********",
        "UserName=ABC"
      ],      
      "scripts": 
      [
        "test.ps1"
      ]
    } ]

.Ps1无法从packer(.json)读取输入参数...

2 个答案:

答案 0 :(得分:0)

与Unix shell脚本不同,Powershell变量(和参数)不是环境变量。

Powershell中用于读取环境变量的语法为$env:variablename


您可以将参数默认值设置为env var:

param(
    [string] $userpassword = $env:userpassword,
    [string] $UserName = $env:username
)

Write-host "Start.." (Get-date)
[...]

或者废弃param块并直接直接分配变量:

[string] $userpassword = $env:userpassword
[string] $UserName = $env:username

Write-host "Start.." (Get-date)
[...]

答案 1 :(得分:0)

虽然问题不是很清楚,但我想从标题中推测出您希望在将参数传递给它的打包程序下运行PowerShell脚本。

Packer确实支持此功能,但仅适用于内联脚本。 参数是环境变量还是直接输入都没有关系。 关键是要确保脚本从建筑机器上运行。

这是一个两步过程。

  1. 将文件复制到计算机上。
  2. 运行文件内联传递参数。

例如

"provisioners": [
     {
      "type": "file",
      "source": "c:\myscripts\MyPowerShellScript.ps1",
      "destination": "c:\temp\MyPowerShellScript.ps1",
      "direction": "upload"
     },
     {
      "type": "shell",
      "inline": [
         "c:\temp\MyPowerShellScript.ps1 Param1 {{user `Param2_from_an_env_var`}}"
       ]
      },