PowerShell script called from within the Jenkins PowerShell build step hangs indefinitely - powershell

I have a Jenkins (1.493) project that uses the Jenkins PowerShell build step to execute a PowerShell script. Inside that script I want to invoke another script that is stored inside a file. I have now reduced it to the following:
Script inside Jenkins PowerShell build step:
& "\\stemmer.local\sidevelopment\cvdev\devbase\jenkins\PowerShell\Test.ps1"
Content of Test.ps1:
write-host 'Hello world!'
Whenever this Jenkins project executes, the PowerShell build step hangs indefinitely.
Things I have tried/verified so far:
Adding some output before the invocation of Test.ps1 shows me that the Jenkins PowerShell script is being execute normally up to the point where Test.ps1 is called.
The file Test.ps1 exists and is reachable from the build slave that executes the script. If I alter the file's name, I get the expected error message from PowerShell...
Exchanging the " for ' in the 1st script does not change anything. Also, using dot-sourcing rather than & does not help.
The file Test.ps1 can be executed properly from the powershell itself using the same command line that is being used in the Jenkins PowerShell script.
The execution policy for PowerShell has been set to unrestricted on my development host as well as on the Jenkins build slave.
I've tried replacing the PowerShell build step with a Windows batch command build step that looks like this:powershell.exe -InputFormat None -File "\\stemmer.local\sidevelopment\cvdev\devbase\jenkins\PowerShell\Test.ps1"and played around a little with the parameters of powershell.exe, but the results were - in those cases that were syntactically and otherwise correct as far as I can tell - always the same.
I only found few references to problems that sounded similar, but none of the approaches mentioned elsewhere did help me fix this. I am absolutely puzzled, and wondering whether someone encountered this issue before (and maybe even got a scenario like the one I have in mind running).
Thanks a lot for any input!
Volker

have you tried to set execution policy to bypass ?
Copy the script file locally, then invoke it from within the Jenkins PowerShell plugin - that way it works as expected.

Related

Jenkins parameter Release versus Staging

I created a freestyle job in Jenkins that I just set up (latest version).
I added parameters to it. One of those is a Options selection for ReleaseType with the options of Staging and Release.
One of the build steps is executing a remote command on the server when the site is uploaded to. It uses the Execute Windows Batch Command build step.
Here is the command line (with things made generic):
sexec myuser#mysite.com -pw=mypassword -cmd="PowerShell -Command ""C:\batch\bvCopyFast.ps1 C:\inetpub\mysite${ReleaseType}\siteLoad C:\inetpub\mysite${ReleaseType}\site""
Basically I am executing a powershell command that uses Robocopy to copy the files from the upload folder to the actual release folder for the site.
As you can see I need to have the ${ReleaseType} replaced with the actual value. The problem is that when this gets executed it isn't doing the substitution. I just uses that literal value in the command and that doesn't work.
If you use the -Command parameter it implies you are going to write raw PowerShell code in between the quotation marks that follow (allow you can call a script as you have).
PowerShell -Command "Get-Date; pause;"
To call a PowerShell script file you should use:
PowerShell -File "Your-Script.ps1 -Parameter1 Argument1 -Parameter2 Argument2"
https://learn.microsoft.com/en-us/powershell/scripting/components/console/powershell.exe-command-line-help?view=powershell-6
I would write a PowerShell script that accepted your root path and the releaseType as arguments and execute that.
Param($rootPath,$releaseType)
{
robocopy "$($rootPath)\$($releaseType)\siteLoad" "$($rootPath)\$($releaseType)\site"
}
I have never used Jenkins so I hope this works as I expect it to!
sexec myuser#mysite.com -pw=mypassword -cmd=""PowerShell -File 'C:\batch\newScript.ps1' -RootPath 'c:\inetpub\mysite' -ReleaseType {ReleaseType}""

Bamboo Powershell Task fails after first run

I'm completely new to Bamboo, so thank you in advance for the help.
I'm trying to create a Bamboo Run that zips files from a git repo and uploads it to Artifactory. Currently my build contains 2 tasks - source code checkout and a simple powershell script. The first time I run it it builds perfectly fine, but without any modifications any consecutive runs fail.
The error I'm getting in the log is the following:
Failing task since return code of [powershell -ExecutionPolicy bypass -Command /bin/sh /opt/bamboo/agent/temp/OR-J8U-JOB1-4-ScriptBuildTask-539645121146088515.ps1] was -1 while expected 0
Replacing the powershell script with empty space does not resolve the issue - only removing the script completely allows the build to succeed, but I cannot reinsert a new script or it will fail. I read other online questions suggesting that I "merge the user-level PATH environment information in to the system-level PATH" but I cannot find the user-level environment information, my environmental variables section is completely empty.
Like Vlad, I found that it was more efficient to implement my powershell script with batch.

Executing powershell command directly in jenkins pipeline

Is it possible to call a PowerShell command directly in the pipelines groovy script? While using custom jobs in Jenkins I am able to call the command with the PowerShell Plugin. But there is no snippet to use this in the groovy script.
I also tried sh() but it seems that this command does not allow multiple lines and comments inside the command.
To call a PowerShell script from the Groovy-Script:
you have to use the bat command.
After that, you have to be sure that the Error Code (errorlevel) variable will be correctly returned (EXIT 1 should resulting in a FAILED job).
Last, to be compatible with the PowerShell-Plugin, you have to be sure that $LastExitCode will be considered.
I have notice that the 'powershell' is now available in pipeline, but since it have several issues I prefer this variant. Still waiting it works stabil. I actually have an issue with the 'dontKillMe' behavior.
Since Jenkins 2.207 with Powershell plugin 1.4, I have replace all my calls with the official powershell pipeline command. I do now recommend to use it.
Note that you must predent \$ErrorActionPreference='Stop'; to your Script if you want it to abort on Write-Error because of an Issue with the powershell plugin.
For that porpuse I have written a little groovy method which could be integrate in any pipeline-script:
def PowerShell(psCmd) {
psCmd=psCmd.replaceAll("%", "%%")
bat "powershell.exe -NonInteractive -ExecutionPolicy Bypass -Command \"\$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$psCmd;EXIT \$global:LastExitCode\""
}
[EDIT] I have added the UTF8 OutputEncoding: works great with Server 2016 and Win10.[/EDIT]
[EDIT] I have added the '%' mask[/EDIT]
In your Pipeline-Script you could then call your Script like this:
stage ('Call Powershell Script')
{
node ('MyWindowsSlave') {
PowerShell(". '.\\disk-usage.ps1'")
}
}
The best thing with that method, is that you may call CmdLet without having to do this in the Script, which is best-praxis.
Call ps1 to define CmdLet, an then call the CmdLet
PowerShell(". '.\\disk-usage.ps1'; du -Verbose")
Do not forget to use withEnv() an then you are better than fully compatible with the Powershell plugin.
postpone your Script with . to be sure your step failed when the script return an error code (should be preferred), use & if you don't care about it.
Calling PowerShell scripts is now supported with powershell step as announced on Jenkins blog.
The documentation mentions it supports multiple lines scripts.
From version 2.28 of Pipeline Nodes and Processes Plugin, we can directly use 'powershell'.
Eg: powershell(". '.Test.ps1'")
You can use the sh command like this:
sh """
echo 'foo'
# bar
echo 'hello'
"""
Comments are supported in here.

TFS2015 Release Management Execute Powershell on Remote Machine

Evening,
I have recently installed TFS2015 and investigating the Release Management integrated solution, but have come across a huge blocker that I just cannot make sense of.
I currently have a RM2013 build working with TFS, RM Server 2013, and Powershell DSC and have setup a new deployment in RM2015, it has a single task in it 'Execute Powershell on Remote Machine' - with a very simple powershell script just writing out a string to the verbose listener.
I have verified that the file is transferred to the Agent working directory as part of the artifact transfer process, and if I call Import-Module "path to script" (Which is what the PowerShellonTargetMachines script seems to do under the hood) in the ISE of the remote server, my script runs perfectly fine - but no matter what I do, in TFS release 2015 I get this error without fail:
[error]The term 'path to script\test.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. For more info please refer to http://aka.ms/powershellontargetmachinesreadme
Now just to double confirm, the path to the scrpt is 100% correct, I have pasted it into a local ISE on the remote server, and it executes perfectly fine - but from TFS2015 Execute Powershell on Remote Server - it simply fails to run, in fact any script I point at fails to run with the exact same error (I initially thought it might be a DSC component install failure, but even with a simple test script the same issue occurs without fail!
My path in the tasks Deployment>Powershell Script parameter input is:
c:\test_scripts\test.ps1
I have tried with quotes, without quotes, dot sourcing - nothing makes a difference which is making me think something fundamentally is either broken with my installation, or I am simply doing this wrong.
Any ideas gratefully received!!!
The script has to already be on the machine. You can push the script using the "Windows Machine File Copy" task.
Fixed this... make sure you execute the PS1 file on the release agent itself unless copying the powershell files to the remote node via file copy first as indicated below

TeamCity running Powershell script, but failing to execute a batch file

I am currently in the process of implementing a deployment method using Teamcity, which runs a Powershell script on my Build Agent, which then configures my Production environment etc.
I have a problem with the Powershell script though, in that it can't seem to run the batch file from it.
The script runs perfectly if I run it manually, it only fails when run via TeamCity.
In the build log I am getting the error:
'myBatchFile.bat' is not recognized as an internal or external command, operable program or batch file.
The batch file and the powershell script are in the same directory and the batch file is called as such:
cmd /c Deploy.bat
I have my TeamCity configuration set up to have the build step for this as:
Script: File
ScriptExecutionMode: Execute script with -File argument
Script Arguments: None
Additional CMD line params: None
I had originally not used the cmd to try to execute the batch file, but executing the batch file like .\Deploy.bat did not seem to work either.
Is there an additional thing I need to set up in order to get the batch file to run? The rest of the script runs fine, just the call to the batch that doesn't.
This is a bit of a wild stab as it's difficult to predict what's happening, but from the description it seems like the path is been altered in the script and it's also dynamic as TeamCity creates temp directories, but if you replace:
cmd /c Deploy.bat
with
cmd /c "$(Split-Path $myinvocation.MyCommand.Path)\Deploy.bat"
then I think this will be able to located the deploy script.
Let me know how it goes.