PowerShell workflow doesn't work in Jenkins? - jenkins

I have a script in PowerShell. It's running from Jenkins via a PowerShell step. Without Jenkins all works fine. But when I build it with Jenkins, I got nothing... no errors, just nothing. What's wrong? Jenkins can't use PowerShell workflow?
Simple example:
workflow config {
Param([string[]]$servers, $MaxEnvSize, $MaxMemPerShell)
$servers = $servers.Trim()
foreach -parallel -throttlelimit 50 ($server in $servers) {
if (Test-Connection -ComputerName $server -Quiet -Count 1) {
inlinescript {
try {
Invoke-Command -ComputerName $using:server -ea Stop -ScriptBlock {
Param($MaxEnvSize, $MaxMemPerShell)
Set-Item WSMan:\localhost\MaxEnvelopeSizekb -EA Stop -Value $MaxEnvSize
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB -EA Stop $MaxMemPerShell
Set-Item WSMan:\localhost\Plugin\Microsoft.PowerShell\Quotas\MaxMemoryPerShellMB -EA Stop $MaxMemPerShell
#Restart-Service winrm
} -ArgumentList $using:MaxEnvSize , $using:MaxMemPerShell
} catch {
"$using:server : $Error[0].Exception"
}
}
} else {
Write-Output "$server no ping"
}
}
}
config -Servers $env:servers -MaxEnvSize 16454 -MaxMemPerShell 5192

By default jenkins will use 32-bit powershell. Powershell workflow is supported only in 64-bit powershell. trigger powershell script using C:\Windows\Sysnative\WindowsPowerShell\v1.0\powershell.exe which will redirect to 64-bit powershell.

Related

Jenkins Parameterized with batch commands or powershell script

I want to add to a pipeline parameters of folders and files in a directory on an agent.
e.g when I click on Build with Parameters it will show my checkbox of all the folders&files at c:\project and then I can choose which files I want for the job.
I try using plugin Active Choices Parameter, and to run a groovy script
node (node1){
stage('folders'){
bat "dir /b /s c:\\project"
}
}
I've tried also with powershell script
Get-ChildItem -path c:/project1 -Recurse -Name
You can do something like below. I don't have WIndows to test. But this should work on Windows as well. Just provide the correct Path.
pipeline {
agent any
parameters { choice(name: 'CHOICES', choices: listFiles("/var/jenkins_home/test"), description: '') }
stages {
stage('Test') {
steps {
echo "Run!!!"
}
}
}
}
#NonCPS
def listFiles(def path) {
def files= []
new File(path).traverse(type: groovy.io.FileType.FILES) { file ->
files.add(file)
}
return files
}

Is there a PowerShell variable that can be checked to see if you the script is running in the Azure cloud shell?

Something similar to $IsLinux or $IsWindows.
From your description, I am not sure how did you run your script. If you use Start-Job to run the PowerShell script as a background job, you could use Get-Job to see the State.
Start-Job -FilePath ./GetDate.ps1
Get-Job
This is an old, but I had the same question and found this environment variable that works for my purposes. I'm not sure if there's another "official" way though.
PS> $env:AZUREPS_HOST_ENVIRONMENT
cloud-shell/1.0
I would suggest running a command in a try/catch that is specific to cloud shell, if that is what you are looking for?
try {
$sessioninfo = Get-CloudDrive
if ($sessioninfo) {
Write-Host "Running in Cloud Shell mode..." -ForegroundColor Green
$path = ($home + "/clouddrive/" + "report" + "-$(get-date -Format yyyyddMM_hhmmtt).csv")
}
}
catch {
Write-Host "Running in local PowerShell session mode..." -ForegroundColor Yellow
$path = "C:\localpath\report"+"-$(get-date -Format yyyyddMM_hhmmtt).csv"
}

can we run workbench toolkit command mqsicreatebar without installation?

Can we build the IIB Bar file( using mqsicreatebar toolkit command) without IIB installation on jenkins box that has workspace code checked out ?
No, you have to install IIB before you can use mqsicreatebar.
Here the important bits of a Jenksfile for a job that runs on Windows:
steps {
script { currentBuild.result = 'SUCCESS' }
bat '''
call "C:/Program Files/IBM/IIB/10.0.0.14/server/bin/mqsiprofile.cmd" || exit /B 1
call mqsicreatebar ...
'''
}

Declarative Jenkins with WithCredentials and Powershell

stage('Deployment') {
steps {
withCredentials([string(credentialsId: 'Test', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
powershell '$pass = ConvertTo-SecureString -AsPlainText "${PASSWORD}" -Force'
powershell '$SecureString = "${pass}"'
powershell '$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "${USERNAME}","${SecureString}"'
powershell 'New-PSSession -ComputerName 192.123.123.123 -Credential "${MySecureCreds}"'
}
powershell 'Copy-Item "${ARTIFACT_PATH}" -Destination "${DESTINATION_PATH}" -ToSession -Recurse -Force'
powershell 'Start-Process "iisreset.exe" -NoNewWindow -Wait'
powershell 'Remove-Website -Name WebCareRecord'
powershell 'Remove-WebAppPool WebCareRecord'
powershell 'Get-WebBinding -Port 85 -Name WebCareRecord | Remove-WebBinding'
powershell 'Start-Process "iisreset.exe" -NoNewWindow -Wait'
powershell 'New-WebAppPool -Name WebCareRecord'
powershell 'Set-ItemProperty "${POOL_PATH}" managedPipelineMode 0'
powershell 'Set-ItemProperty "${POOL_PATH}" managedRuntimeVersion ""'
powershell 'New-WebSite -Name WebCareRecord -Port 85 -PhysicalPath "${PHYSICAL_PATH}" -ApplicationPool WebCareRecord'
powershell 'Start-Process "iisreset.exe" -NoNewWindow -Wait'
}
}
I am trying to get the Jenkins credentials ID, secure it and use the same credentials to login into the remote server. After login to the remote server, copy the artifact from jenkins server to remote server. For this I am getting error
org.jenkinsci.plugins.credentialsbinding.impl.CredentialNotFoundException: Credentials 'Test' is of type 'Username with password' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected.
There might be multiple problems, I've going through similar process now and feeling the pain to get it correctly in powershell within groovy, so this is what I've noticed so far:
You are creating a $pass variable in one powershell step, and then trying to access it in another powershell step, I don't think it will work that way, as another step might launch in different powershell session and that powershell variable is no longer there.?
I would try something like this:
stage('Deployment') {
steps {
withCredentials([string(credentialsId: 'Test', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
powershell """
\$pass = ConvertTo-SecureString -AsPlainText $PASSWORD -Force
\$SecureString = \$pass
"""
}
}
}
So first of all you use multiline syntax """ so the different powershell statements are in the same session, and those variables are available across powershell commands.
Second, you escape powershell variables \$pass and \$SecureString, so groovy does not try to expand them, and you don't escape variables where you are actually referring to groovy variables like $PASSWORD.
Note that $PASSWORD does not have to be in quotes, since powershell parameters can accept strings without quotes, but if this was used in a method you should put it into quotes SomePowershellMethod("$GROOVYVAR").
In general I suggest to echo every variable while troubleshooting, to see if you are getting what you are expecting.
I like short and precise answer.
Use following :
stage('Deployment') {
steps {
withCredentials([usernamePassword(credentialsId: 'UatServer', passwordVariable: 'passVar', usernameVariable: 'userVar')]) {
powershell '''
$passVar = ConvertTo-SecureString "$($ENV:passVar)" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ("$ENV:userVar", $passVar)
$session = New-PSSession -ComputerName x.x.x.x -Credential $credential
Invoke-Command -Session $session -ScriptBlock {hostname}
'''
}
}
}

I want to check whether a job with specified name is running in powershell, if so remove the job using Remove-Job

$abc={script}
Start-Job $abc -name MyTask
The script runs in the background for a long time and hence I want to remove it when it's still running. when I try to remove the job using Remove-job -name MyTask -force, it throws an error if the job was already removed. So I need an
If(Check the job name exist)
{
Remove-job -name MyTask -force
}
try:
if ( [bool](get-job -Name MyTask -ea silentlycontinue) )
{
...
}
else
{
...
}

Resources