jenkins cannot execute powershell under program files - powershell

I am using Jenkins for deployment. I wanted to run a powershell script that copies some files. I have installed "Windows Powershell" plugin for jenkins that will execute the powershell script. My Powershell script looks like below
param (
[string] $targetEnvironment,
[switch] $WhatIf,
[switch] $Compare)
try
{
#do smething here
}
catch
{
}
This script is working fine when i execute it manually. However when run the script using the following command in plugin's input window i get error
Note that, if i copied the "deploymentscript" folder to "C:\deploymentscript" and then change the path in plugin's window then the job runs fine.
It doesnt work when its executing under program files
The error im getting is
First time build. Skipping changelog.
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\CODESC~1\AppData\Local\Temp\hudson2119904511537985474.ps1'"
At C:\Users\username\AppData\Local\Temp\hudson2119904511537985474.ps1:1 char:119
+ ... etaTaskar.ps1' -targetEnvironment demo
+ ~~~~~~~~~~~~~~~~~~
Unexpected token '-targetEnvironment' in expression or statement.
At C:\Users\username\AppData\Local\Temp\hudson2119904511537985474.ps1:1 char:138
+ ... getEnvironment demo
+ ~~~~
Unexpected token 'demo' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
Build step 'Windows PowerShell' marked build as failure
Finished: FAILURE
EDIT1
#petrik You are right, the space in the "Program Files (x86)" folder causing the issue. The solution is to use the following foormat
&("C:\Program Files (x86)\Jenkins\jobs\MyJob\workspace\crconfig\deploymentscript\Deploy.ps1") -targetEnvironment demo
and that works.
Now based on the article here if the powershell scrit fails i want the Jenkin's job to fail too,
So i have tell Hudson to call the powershell script form a windows batch task.
powershell "& {&('C:\Program Files (x86)\Jenkins\jobs\MyJob\workspace\crconfig\deploymentscript\Deploy.ps1') -targetEnvironment $Env:EnvironmentParam; exit $lastexitcode }"
I am not sure if i really need to this in my case ??

So in this case the problem is caused by the fact that the 'Program Files' path has spaces in it. Putting the path to the script into a variable which can then be executed using the call operator.
In order to ensure that Jenkins fails the build if the Powershell script fails several steps need to be taken.
Use the Jenkins powershell plugin. It will pass the powershell exit code on to Jenkins
Set the $ErrorActionPreference to 'Stop' as early as possible. This forces Powershell to halt when exceptions are thrown. The default behaviour is to report the error but then continue.
The script in the Jenkins configuration could look like this:
$ErrorActionPreference = 'Stop'
$scriptPath = 'c:\Program Files (x86)\Jenkins\jobs\MyJob\workspace\crconfig\deploymentscript\deploy.ps1'
& $script -targetEnvironment 'demo'
This should make Jenkins run the script correctly and report an error and stop the build if the script fails.

I did two things to resolve issue:
1) Appended the path to powerscript "c:\Users\\Documents\WindowsPowerShell\profile.ps1" to path variable of system properties.
2) Opened Powershell with administrative permissions and executed: "Set-ExecutionPolicy Unrestricted"
Then restarted windows machine. When i reconnected it to jenkins, my powershell just worked fine.

Related

Newbie powershell argument issues

I made powershell script that [1] accepts 2 arguments (aka parameters), [2] changes a file's modified date & time, and [3] writes something to host. The following command line works just fine in the powershell console, but triggers an error message when I run the same command line in a Windows cmd prompt (DOS) Window:
E:\Apps\UtilitiesByMarc\Change_DateTime_for_test1.bat_and_Hello_world_with_2_named_args_aaa.ps1 -dateTimeVarArg "01/11/2005 06:01:36" -file_dateTimeMod_fullname "E:\Apps\Delete01\test1.bat"
The following is the coding for the powershell script to which I gave the long name, 'Change_DateTime_for_test1.bat_and_Hello_world_with_2_named_args_aaa.ps1':
param ( [string]$dateTimeVarArg, [string]$file_dateTimeMod_fullname)
Get-ChildItem $file_dateTimeMod_fullname | % {$_.LastWriteTime = $dateTimeVarArg}
#Get-ChildItem "E:\Apps\Delete01\test1.bat" | % {$_.LastWriteTime = $dateTimeVarArg}
$strString = "Hello World"
write-host $strString
function ftest{
$test = "Test"
write-host $test
}
ftest
When I run the command line shown above in a Windows DOS command prompt setting, I get the following error message:
Exception setting "LastWriteTime": "Cannot convert null to type "System.DateTime"."
At E:\Apps\UtilitiesByMarc\Change_DateTime_for_test1.bat_and_Hello_world_with_1_named_arg_aaa.ps1:6 char:50
+ ... "E:\Apps\Delete01\test1.bat" | % {$_.LastWriteTime = $dateTimeVarArg}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
I would like to know [1] how to alter the command line shown above (which works fine in the powershell console) so that it works in a Windows DOS command prompt setting, and [2] where I can learn more about why my command line triggers errors, and how to avoid them.
According to the output from the command "Get-Host | Select-Object Version", I am running version. 5.1.19041.1682.
Any tips would be much appreciated.
By default, you can not directly execute PowerShell scripts (.ps1 files) from cmd.exe, the Windows legacy shell, or from outside PowerShell altogether.
Attempting to do so opens the script file for editing instead, as does double-clicking .ps1 files from File Explorer / the desktop.
Executing .ps1 scripts from outside PowerShell itself requires use of the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+), which in your case translates to a call such as (additional CLI parameters may be called for):
powershell.exe -File E:\Apps\UtilitiesByMarc\Change_DateTime_for_test1.bat_and_Hello_world_with_2_named_args_aaa.ps1 -dateTimeVarArg "01/11/2005 06:01:36" -file_dateTimeMod_fullname "E:\Apps\Delete01\test1.bat"
As for what you tried:
The fact that you were able to execute your .ps1 from cmd.exe suggests that you changed the file-type definition for such files to execute via powershell.exe instead.
The fact that the arguments you tried to pass to the script were ignored - as implied by the error message you got - suggests that you used File Explorer's Open with shortcut-menu command to choose to open all .ps1 files with powershell.exe; said method does not support argument-passing.
There is a way to change the file-type definition to support argument-passing too, and it is detailed in this answer (section "Programmatic method").
Generally, however, I suggest not applying this customization, especially in batch files that must also be run by other users / on other machines, which cannot be expected to have the same customization in place.

Powershell script run by release agent throws exception because missing .net standard 2.0

I try to run the script
Backup-SqlDatabase -ServerInstance "myserver" -Database "mydd" -BackupFile "\\mypath.bak"
This works when I log into the release target and execute the script interactively.
If I turn it into a PowerShell task in a release pipeline I get the exception
Could not load file or assembly "netstandard, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" or one of its
dependencies. The specified module could not be found.
In C:\Program Files\WindowsPowerShell\Modules\SqlServer\21.1.18221\SqlServer.psm1:61
Zeichen:25
+ ... $binaryModule = Import-Module -Name $binaryModulePath -PassThru
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand
Process completed with exit code 0 and had 1 error(s) written to the
error stream.
I also run the PowerShell console as the user that the release agents runs as and it worked. How can I further debug this issue?
I have on premise release agents and build agents.
I also run the PowerShell console as the user that the release agents runs as and it worked. How can I further debug this issue?
According to the troubleshooting you did, it seems that the difference between powershell task and private agent powershell is causing this issue.
When I use the powershell task, we could found it not use the powershell from the priavte agent:
As workaround, you could try to use the command line task invoke the powershell from the private agent, like:
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass .\Test.ps1
Hope this helps.

Octopus Deploy not running PowerShell script

I have a Process Step in Octopus Deploy to run some Selenium WebDriver tests by calling a PowerShell script but it results in an error.
The PowerShell script is as follows:
set nunitPath="C:\AutomatedTests"
cd %nunitPath%\
nunit-console SiteCore.nunit /include:BulkyWasteTests
When the deployment takes place and the Process Step to run the script takes place, the following error occurs:
Set-Location : Cannot find path 'C:\Octopus\Work\20170110115049-7\%nunitPath%\' because it does not exist.
At C:\Octopus\Work\20170110115049-7\Script.ps1:2 char:3
+ cd %nunitPath%\
+ CategoryInfo : ObjectNotFound: (C:\Octopus\Work...-7\%nunitPath %\:String) [Set-Location], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
The remote script failed with exit code 1
I don't understand why the error is reporting a different location to the location specified in the PowerShell script.
Any help greatly appreciated.
cd is an alias for Set-Location, so you can tell that it's the second line you need to change by looking at the error. Your cd line is trying to set the location to the %nunitpath% environment variable rather than the nunitPath script variable.
To reference the script variable use $nunitpath
So your script should look like:
set nunitPath "C:\AutomatedTests"
cd $nunitpath
nunit-console SiteCore.nunit /include:BulkyWasteTests
Edited with #4c74356b41 additional correct comment.
PowerShell doesn't use %variablename% syntax for expanding environment variable references in a string. That's cmd.exe syntax. In PowerShell, write $env:variablename instead.

TeamCity Powershell Runner - Unable to run Source Code

Im trying to run some PS scripts using the Powershell Runner in TC and defining my own script as "Source Code" instead of a script file.
My script is as simple as:
"Hello World!"
Im running on Windows Server 2008 R2 and ive tried with to:
Run it as x86 + x64
Using "Execute .ps1 with '-File' argument" + "Put script into powershell stdin with "-Command -" arguments.
Ive set the security policy to Unrestricted in an attempt to get it to work, but no luck.
If I instead use a Command Line runner and for example writes:
powershell -Command Get-ExecutionPolicy
It works fine.
The errors im getting (depending on which of the 2 execution modes im using) are:
Starting: C:\...\cmd.exe /c C:\...\powershell.exe -NonInteractive -Command
- "<C:\...\powershell3889347351955805274.ps1" && exit /b %ERRORLEVEL%
in directory: C:\...\e18dda4054c166c7
'-' was specified with the -Command parameter; no other arguments to -Command are permitted.
OR
Starting: C:\...\cmd.exe /c C:\...\powershell.exe -NonInteractive -File
"C:\...\powershell8264270201473986040.ps1" && exit /b %ERRORLEVEL%
in directory: C:\...\e18dda4054c166c7
The term 'f' is not recognized as the name of a cmdlet, function, script file,
It looks to me like TC puts something in the actual script itself, but im not sure. Im stuck and I cant figure out what point im missing here :S.
Can anyone help?
I wasn't able to reproduce this, but I noticed something pretty weird with the command that TeamCity was trying to run:
-NonInteractive -Command - "<C:\...\powershell3889347351955805274.ps1"
I did not see it adding the quotes for me, so I thought maybe TeamCity is trying to quote a path with space(s) in it ( would have helped if you hadn't redacted your path)
So I switched my agent to a path with a space in it and I got the same command, and yes, the same error. So TeamCity is quoting the path wrongly. It is including the < in the quotes while it should have been <"c:\path with\space"
I will see if I can file a bug for this ( if there isn't one)
Try moving your agent to a non-space path as a workaround.

PowerShell Script in PostBuild

Continuous Integration
I have been working on a PowerShell script to keep our development process streamlined. I was planning on running it as a post-build event, but I'm having some trouble.
From the PowerShell prompt, the following works wonderfully:
PS C:\> ./example.ps1
However, when attempting to run this from cmd.exe as follows:
C:\> powershell -command "&\"C:\path to script\example.ps1\""
The script executes but I get a round of errors back from PowerShell, consisting mostly of path resolution errors from the resolve-path function:
Resolve-Path : Cannot find path 'C:\Documents and Settings\bdunbar\My Documents
\Visual Studio 2008\Projects\CgmFamilyComm\FamilyComm\iirf\cms\isapirewrite4.dl
l' because it does not exist.
At C:\Documents and Settings\bdunbar\My Documents\Visual Studio 2008\Projects\C
gmFamilyComm\scripts\cms.ps1:4 char:27
+ $iirfpath = (resolve-path <<<< ../iirf/cms/isapirewrite4.dll).path,
Resolve-Path : Cannot find path 'C:\Documents and Settings\bdunbar\My Documents
\Visual Studio 2008\Projects\CgmFamilyComm\FamilyComm\familycomm' because it do
es not exist.
At C:\Documents and Settings\bdunbar\My Documents\Visual Studio 2008\Projects\C
gmFamilyComm\scripts\cms.ps1:5 char:27
+ $vdirpath = (resolve-path <<<< ../familycomm).path
Is there a way to work around this? Could it be an issue with running resolve-path under cmd.exe?
[Update]
I've been able to change things to get around the errors that are occurring, but I still receive errors that work perfectly fine from the powershell command prompt. I can't figure out what the difference is.
I've made this work in the past (see http://sharepointpdficon.codeplex.com/SourceControl/changeset/view/13092#300544 if interested):
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -NoLogo
-NonInteractive -Command .'$(ProjectDir)Deployment\PostBuildScript.ps1'
-ProjectDir:'$(ProjectDir)' -ConfigurationName:'$(ConfigurationName)' -TargetDir:'$(TargetDir)' -TargetFileName:'$(TargetFileName)' -TargetName:'$(TargetName)
Then throw these parameters in the first line of your post-build script (if you think you may be able to use them):
param($ProjectDir, $ConfigurationName, $TargetDir, $TargetFileName)
Also I should point out, I am not using this presently. I did like using it as a quick scratchpad to reload test data for running integration tests.
Looks like your problem is how relative paths are resolved. Relative paths are resolved based on the current location (stored in $pwd) and not based on the location of the script. So if you launched the script from C:\, it definitely would not work.
I would suggest you calculate the paths based on an argument (like Peter Seale shows), or grab the actual location of the script from:
$MyInvocation.MyCommand.Path