如何将秘密类型变量传递给脚本?

时间:2019-06-13 00:51:58

标签: powershell tfs

我定义了一些构建定义变量,其中一些是秘密类型。

我正在尝试将机密变量$RPASS传递给TFS上的内联Powershell脚本任务,但似乎不起作用。

我在这里看过这篇文章:How to add secret variable as task environment variable in VSTS

但是,示例使用命令行。

是否可以在Powershell内联任务中传递类似的参数?

$sec = New-Object -TypeName System.Security.SecureString
"$RPASS".ToCharArray()|%{$sec.AppendChar($_)}
$creds = new-object -typename System.Management.Automation.PSCredential -args "$env:USER", $sec
Send-MailMessage -From "tfs@domain.com" -Subject "YAY!" -To "user@domain.com" -Body "$env:DB_NAME" -SmtpServer server.com -Port 25 -Credential $creds

在该帖子的第二个答案之后,我尝试传递参数

$(RPASS)

arg

,然后更改此行$arg[0].ToCharArray()|%{$sec.AppendChar($_)}

但是那也不起作用

  

[错误]无法索引到空数组。

我尝试这样直接将其传递到脚本中:

$(RPASS).ToCharArray()|%{$sec.AppendChar($_)}

但是导致错误:

+ ********.ToCharArray()|%{$sec.AppendChar($_)}
+                                 ~
An expression was expected after '('.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : ExpectedExpression


2019-06-13T00:57:50.7974750Z ##[error]Process completed with exit code 0 and had 1 error(s) written to the error stream.

2 个答案:

答案 0 :(得分:1)

在嵌入式脚本中使用ConvertTo-SecureString

$securePassword = ConvertTo-SecureString -String "$(RPASS)" -AsPlainText -Force
$creds = [System.Management.Automation.PSCredential]::new($env:USERNAME, $securePassword)

您不需要传递参数,因为TFS会解析内联脚本中的变量

答案 1 :(得分:1)

您应该在参数中传递它,但还需要在脚本中添加一个参数:

Param (
 [string]$RPASS
)
$sec = New-Object -TypeName System.Security.SecureString
$RPASS.ToCharArray()|%{$sec.AppendChar($_)}

然后在“参数”字段中传递变量:

-RPASS $(RPASS)

enter image description here

您可以看到,如果我只做$RPASS.ToCharArray(),我会看到秘密变量:

enter image description here

enter image description here

相关问题