Powershell script in declarative jenkins pipeline
In case someone is here, and still trying to figure out what is the issue. I will share the solution that worked for me.
Use escaping before variable "$" sign in multi-line string.
powershell (""" \$psw = ConvertTo-SecureString -String \$CREDENTIAL_PSW -AsPlainText -Force \$mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList \$CREDENTIAL_USR, \$psw -Verbose Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force \$session = New-PSSession -ComputerName "192.111.111.111" -Credential \$mySecureCreds""")
At the moment you're running each line in its own powershell process, so the results of the line before are not available to the next command.
I think you just need to move the script into a multi-line string:
powershell (""" $psw = ConvertTo-SecureString -String $CREDENTIAL_PSW -AsPlainText -Force $mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CREDENTIAL_USR, $psw -Verbose Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force $session = New-PSSession -ComputerName "192.111.111.111" -Credential $mySecureCreds""")
You can easily run multiline powershell commands in jenkins pipeline like this. Example, if you want to login to azure using service principal, you'll do something like below:
powershell ''' $pass = ConvertTo-SecureString your_client_secret -AsPlainText –Force $cred = New-Object -TypeName pscredential –ArgumentList your_client_id, $pass Login-AzureRmAccount -Credential $cred -ServicePrincipal –TenantId your_tenant_id -vaultName "eusdevmbe2keyvault" -name "normalizedcontainername").SecretValueText '''
Check here for reference https://jenkins.io/blog/2017/07/26/powershell-pipeline/