syntax to include Jenkins pipeline optional argument - powershell

I currently have a sample pipeline that works but in the Jenkins output does not return the confirmation that the script worked.
pipeline {
agent any
environment {
CRED_APP_CATALOG = credentials('id-app-tenant')
}
stages {
stage('ConnectToApp'){
steps {
script{
pwsh '''
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $env:CRED_APP_CATALOG_USR , $(convertto-securestring $env:CRED_APP_CATALOG_PSW -asplaintext -force)
Connect-PnPOnline -Url $env:app_catalog_path -Credentials $cred
Add-PnPApp -Path "./sharepoint/solution/samplesolution.sppkg" -Publish -Overwrite
'''
}
}
}
}
}
I know I need to add the returnStdout from pwsh script some where, but I cant seem to find the syntax any where.

This is the syntax to use:
pwsh returnStdout: true, script: '''
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $env:CRED_APP_CATALOG_USR , $(convertto-securestring $env:CRED_APP_CATALOG_PSW -asplaintext -force)
Connect-PnPOnline -Url $env:app_catalog_path -Credentials $cred
Add-PnPApp -Path "./sharepoint/solution/samplesolution.sppkg" -Publish -Overwrite
'''
Alternatively you may use parentheses:
pwsh( returnStdout: true, script: '''
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $env:CRED_APP_CATALOG_USR , $(convertto-securestring $env:CRED_APP_CATALOG_PSW -asplaintext -force)
Connect-PnPOnline -Url $env:app_catalog_path -Credentials $cred
Add-PnPApp -Path "./sharepoint/solution/samplesolution.sppkg" -Publish -Overwrite
''')
With both syntaxes, you may store the output in a variable for further processing:
def stdout = pwsh returnStdout: true, script: '''
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $env:CRED_APP_CATALOG_USR , $(convertto-securestring $env:CRED_APP_CATALOG_PSW -asplaintext -force)
Connect-PnPOnline -Url $env:app_catalog_path -Credentials $cred
Add-PnPApp -Path "./sharepoint/solution/samplesolution.sppkg" -Publish -Overwrite
'''
echo stdout

Related

"Start-Process : This command cannot be run due to the error: Access is denied." when specifying credentials?

Good morning :S.
I can enter into a PSSession and execute cmdlets just fine, however, as soon as I specify an account to use, it just throws back an access is denied error. I've even tested with the same account and password that established the PSSession. This works locally just fine.
I am trying to integrate this into an SCCM application, so there isn't a whole lot of wiggle room.
EDIT: I put an easier code that doesn't work either below:
$username = 'DOMAIN\Username'
$password = 'P#ssword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process Notepad.exe -Credential $credential
#Execute variable
$myCommand = "'C:\Program Files (x86)\PGP Corporation\PGP Desktop\pgpwde' --status --disk 0"
#Credential Variables
$username = 'DOMAIN\USERNAME'
$Password = ConvertTo-SecureString -String 'P#ssword' -Force -AsPlainText
$credential = New-Object System.Management.Automation.PsCredential -ArgumentList $username, $Password
#Expression Variable
$expression = #"
try
{
& $myCommand | Out-File `C:\test.txt -Force
}
catch
{
`$_.Exception.Message | Out-File `C:\ERROR.txt -Force
}
"#
#Execute
Start-Process powershell.exe -ArgumentList "-c $expression" -Credential $credential

Remove File on SFTP using Powershell

I'm struggling with the below code. Want to delete a file that is on SFTP. Unable to understand how to accomplish this -
$UserName = 'test'
$SecurePassword = ConvertTo-SecureString -String '3ea5e#9dkdadfsfwC' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
$Session = New-SFTPSession -ComputerName 'sftp.test.com' -Credential $Cred
$result = Remove-Item -LiteralPath "\\?sftp://test#sftp.test.com/export/home/dmsmaster/stms/PF/Working_Titles_Primary.csv" -Force
Used the following code to make it work -
$result = Remove-SFTPItem -path "/export/home/dmsmaster/stms/PF/Working_Titles_Primary.csv" -SFTPSession $Session -Force

Powershell script in declarative jenkins pipeline

I am using environment credential to get the username and password. When I echo them they are printed perfectly as ****.
The next comes the powershell commands, when I run them separately, all the commands works perfectly. But through Jenkins pipeline it throws me the following error:
groovy.lang.MissingPropertyException: No such property: psw for class: groovy.lang.Binding
Can anyone explain is this correct way to incorporate powershell in Jenkins pipeline?
environment {
CREDENTIAL = credentials('Test')
}
stage('Deployment') {
steps {
echo "$CREDENTIAL_USR"
echo "$CREDENTIAL_PSW"
powershell """($psw = ConvertTo-SecureString -String $CREDENTIAL_PSW -AsPlainText -Force)"""
powershell """($mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CREDENTIAL_USR, $psw -Verbose)"""
powershell """(Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force)"""
powershell """($session = New-PSSession -ComputerName "192.111.111.111" -Credential $mySecureCreds)"""
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
""")
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/
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
""")

Passing parameters to Invoke-Command

I'm having issues passing parameters to Invoke-Command, I've tried using -Args and -ArgumentList to no avail.
function One {
$errcode = $args
$username = "Ron"
$password = ConvertTo-SecureString -String "Baxter" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$cred
$Result = Invoke-Command -ComputerName MyPc -ScriptBlock { & cmd.exe /c "C:\Scripts\test.bat" Param1 $errcode ; $lastexitcode} -Credential $cred
echo $result
}
One 10
You can update your function to pass in your parameter as $errcode rather than using $args, this is better code as it's less confusing. (I'd recommend readng up on parameters and functions as it'll certainly help)
Then you need to pass $errcode into Invoke-Command using the ArgumentList parameter, and use $args[0] in its place:
function One ($errcode) {
$username = "Ron"
$password = ConvertTo-SecureString -String "Baxter" -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$Result = Invoke-Command -ComputerName MyPc -ScriptBlock { & cmd.exe /c "C:\Scripts\test.bat" Param1 $args[0] ; $lastexitcode} -Credential $cred -ArgumentList $errcode
echo $Result
}
One 10

select multiple switch statements

I have the script below that lets me switch between the different elements and runs the functions in them one by one.
But what I need to do now is make it so I can select multiple ones and have them run and pause between them to verifiy if things were loaded correctly. So that way I don't run into the issue having to re rerun the full script again and redo the same one over.
Can anybody show me how to do this? I am lost as to how to get this completed and working properly.
write-host "Sets up location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (TV30/TV30BP/TV30LM/TV30PV/LT101/XR2/MU11/SAP)"
while ($ElementDistro -notmatch "^(TV30|TV30BP|TV30LM|TV30PV|LT101|XR2|MU11|SAP)$")
{
write-host "you have enterd an error" -ForegroundColor Red
write-host "You must type TV30 or TV30BP or TV30LM or TV30PV or LT101 or XR2 or MU11 or SAP"
write-host "you typed $ElementDistro"
write-host "set location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (TV30/TV30BP/TV30LM/TV30PV/LT101/XR2/MU11/SAP)"
}
switch ($ElementDistro)
{
'TV30'
{
# Do TV30 Stuff
write-host "you have entered TC TV30"
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'TV30BP'
{
# Do TV30BP Stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
# exit-pssession
break
}
'TV30LM'
{
# Do TV30LM stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'TV30PV'
{
# Do TV30PV stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'LT101'
{
# Do LT101 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'XR2'
{
# Do XR2 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'MU11'
{
# Do TF10 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'SAP'
{
# Do SAP stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
}
break
}
If you got at least V3, you can use Out-GridView with -OutPutMode Multiple as a menu to select multiple items from:
$Menu = 'TV30','TV30BP','TV30LM','TV30PV','LT101','XR2','MU11','SAP','ALL'
$Choices = $Menu | Out-GridView -OutputMode Multiple -Title 'Select Locations you want to run staging, and click OK.'
Switch ($Choices)
{
.....
The quick answer is that Powershell's switch statement accepts an array for input. If you leave out the break statement at the end of each switch case it will execute each case that is a match. Enter your choices as a comma-separated list and put them into an array using the split statement.
Each choice in you $Choices array will be executed. If you put a Pause statement where your break statements are you can pause at the completion of each step.
$Choices = #('TV30','MU11')
switch ($Choices)
{
'TV30' {some code}
'TV30BP' {some code}
'MU11' {some code}
}