简体   繁体   English

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

[英]PowerShell script with input parameters with packer(.json)

I have this Ps1 script, 我有这个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) as follows: packer(.json)如下:

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

.Ps1 can not read input para from packer(.json)... .PS1无法从Packer(.json)读取输入参数...

Unlike a Unix shell script, Powershell variables (and params) aren't environment variables. 与Unix Shell脚本不同,Powershell变量(和参数)不是环境变量。

The syntax in Powershell for reading an environment variable is $env:variablename . Powershell中用于读取环境变量的语法为$env:variablename


You can either set the param default values to be the env var: 您可以将参数默认值设置为env var:

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

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

Or scrap the param block and just assign the variables directly: 或废弃参数块,然后直接直接分配变量:

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

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

Whilst the question is not very clear I surmise from the title that you wish to run a PowerShell script under packer passing parameters to it. 尽管问题不是很清楚,但我想从标题中推测出您希望在向参数传递参数的打包程序下运行PowerShell脚本。

Packer does support this but only for inline scripts. Packer确实支持此功能,但仅适用于内联脚本。 It does not matter if the parameter is an environment variable or direct entry. 参数是环境变量还是直接输入都没有关系。 the key thing is to ensure that the script runs from the building machine. 关键是要确保脚本从建筑机器上运行。

It's a 2 step process. 这是一个两步过程。

  1. Copy the file up to the machine. 将文件复制到机器上。
  2. Run the file inline passing params. 运行文件内联传递参数。

Eg 例如

 "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`}}" ] }, 

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

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