2

I defined some build definition variables, of which some i made as secret type.

I am trying to pass the secret variable $RPASS to an inline powershell script task on TFS, but it appears thats not working.

I looked at this post here: How to add secret variable as task environment variable in VSTS

however , the examples use command line.

is it possible to pass arguments like that in a powershell inline task?

$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

Following the second answer in that post, i tried passing in the arguments

$(RPASS)

arg

and then changed this line $arg[0].ToCharArray()|%{$sec.AppendChar($_)}

but that didnt work either

[error]Cannot index into a null array.

I tried passing it directly into the script as so:

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

but that resulted in error:

+ ********.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.
Cataster
  • 3,081
  • 5
  • 32
  • 79

2 Answers2

1

Use ConvertTo-SecureString in your inline script:

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

You don't need to pass the argument, because TFS will resolve the variable in the inline script

mhu
  • 17,720
  • 10
  • 62
  • 93
  • So I can eliminate this line? .ToCharArray()|%{$sec.AppendChar($_)} – Cataster Jun 13 '19 at 13:24
  • You don't need that anymore. These two lines create the credential object, which can be used with the Send-MailMessage cmdlet – mhu Jun 13 '19 at 13:41
1

You should pass it in the arguments but you also need to add a param in the script:

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

And in the "Arguments" field pass the variable:

-RPASS $(RPASS)

enter image description here

You can see, if I only do $RPASS.ToCharArray() I will see the secret variable:

enter image description here

enter image description here

Shayki Abramczyk
  • 36,824
  • 16
  • 89
  • 114