I want custom script when my dotnet build command failed.
How to get errors list or not success flag when the 'dotnet build' failed with errors compilation for example, or when 'dotnet test' failed, with powershell.
I want equivalent code
dotnet test
if (!$result.Successful) {
$errorMessage = ""
if ($result.Error -ne $null) {
$errorMessage = $result.Error.Message
}
Write-Host "##vso[task.logissue type=error;] error"
Write-Host "##vso[task.complete result=Failed;]"
Exit -1
}
You can merge the standard output and error streams with the > stream redirection operator, and then inspect the $LASTEXITCODE automatic variable to see if the call succeeded or not:
# Merge all streams into stdout
$result = dotnet test *>&1
# Evaluate success/failure
if($LASTEXITCODE -eq 0)
{
# Success
}
else
{
# Failed, you can reconstruct stderr strings with:
$ErrorString = $result -join [System.Environment]::NewLine
}
For me it worked by just using exec in PS.
exec { dotnet build $projectFile -o $targetDir -c Release }
Related
I need to compress a data folder in SSIS.
For that, I use a Script task which runs this script :
public void Main()
{
// TODO: Add your code here
try
{
string zipPath = (string)Dts.Variables["User::sFolderCompressed"].Value;
string startPath = (string)Dts.Variables["User::sFolderSource"].Value;
ZipFile.CreateFromDirectory(startPath, zipPath);
}
catch (Exception objException)
{
Dts.TaskResult = (int)ScriptResults.Failure;
// Log the exception
}
Dts.TaskResult = (int)ScriptResults.Success;
}
The 2 variables I have set up:
Executing the Script Task step gives me the following error:
{System.DllNotFoundException: Unable to load DLL 'clrcompression.dll':
The specified module could not be found. (Exception from HRESULT:
0x8007007E) at Interop.inflateInit2_(Byte* stream, Int32
windowBits, Byte* version, Int32 stream_size) at
System.IO.Compression.ZipFile.Open(String archiveFileName,
ZipArchiveMode mode, Encoding entryNameEncoding) at
System.IO.Compression.ZipFile.DoCreateFromDirectory(String
sourceDirectoryName, String destinationArchiveFileName, Nullable`1
compressionLevel, Boolean includeBaseDirectory, Encoding
entryNameEncoding) at
System.IO.Compression.ZipFile.CreateFromDirectory(String
sourceDirectoryName, String destinationArchiveFileName) at
ST_19ce97c462f844559ec30884173f5a28.ScriptMain.Main() in
c:\Users\SQL\AppData\Local\Temp\3\Vsta\46892b1db29f45f2a8e1fb8c5d37a542\ScriptMain.cs:line
104}
Error message is pretty clear that I am missing a 'clrcompression.dll' file somewhere.
Can I just download this DLL? and where do I copy it to?
UPDATE
Added 'Execute Process Task' and set the following:
Executable : 'powershell.exe'
Arguments : -nologo -noprofile
-command "Compress-Archive -Path E:\Flat Files\IT\StockAge\Stock Age Difference\MAINCHECKK807Babbage\BabbageStockAgeingPartno.csv
-DestinationPath E:\Flat Files\IT\StockAge\Stock Age Difference\MAINCHECKK807Babbage\BabbageStockAgeingPartno.zip"
But getting error:
[Execute Process Task] Error: In Executing "powershell.exe" "-nologo
-noprofile -command "Compress-Archive -Path E:\Flat Files\IT\StockAge\Stock Age
Difference\MAINCHECKK807Babbage\BabbageStockAgeingPartno.csv
-DestinationPath E:\Flat Files\IT\StockAge\Stock Age Difference\MAINCHECKK807Babbage\BabbageStockAgeingPartno.zip"" at "",
The process exit code was "1" while the expected was "0".
UPDATE 2
Executing the script in PowerShell gives me the following error.
Script tasks only have access to the DLL's that have been registered in your GAC or have been manually loaded within the script. If you want to use a script task you'll need to load the DLL for the script to be able to run
Alternatively for basic zip functionality you can use a command line tools and call it from an execute process task. If you have the latest windows server running with all the .net frameworks installed you can try the PowerShell method, else use the 7zip method
PowerShell Zip Method
Set up the the execute task so that it calls PowerShell and passes your zip instruction in the arguments
Executable = 'powershell.exe'
Arguments = Powershell -nologo -noprofile -command 'Compress-Archive -Path \"C:\SO\Test Folder\Test.txt\" -DestinationPath \"C:\SO\Test Folder\Test.zip\"'
Edit 1
If your paths have spaces then you need to escape them with backslash and double quotes
Your Arguments should be
-nologo -noprofile -command 'Compress-Archive -Path \"E:\Flat Files\IT\StockAge\Stock Age Difference\MAINCHECKK807Babbage\BabbageStockAgeingPartno.csv\" -DestinationPath \"E:\Flat Files\IT\StockAge\Stock Age Difference\MAINCHECKK807Babbage\BabbageStockAgeingPartno.zip\"'
Edit 2
To debug the command try running it in PowerShell as below, see if there are any additional information
7Zip Method
Install 7zip 64bit on all the servers this package will be running on
You need to ensure that the install directory matches between servers or else ssis will not find the executable when deployed
Executable = C:\Program Files\7-Zip\7z.exe
Arguments = a -r "C:\SO\Test Folder\Test.zip" "C:\SO\Test Folder\Test.txt"
clrcompression.dll
is a part of .NET Framework.
I think you need to check .NET Framework installation on your machine.
I wants to checkout the branch and commit the code changes using powershell script. This powershell script will be called from c# code.
But some times i'm getting the following issue
fatal: remote error: CAPTCHA required Your Bitbucket account has been
locked. To unlock it and log in again you must solve a CAPTCHA. This
is typically caused by too many attempts to login with an incorrect
password. The account lock prevents your SCM client from accessing
Bitbucket and its mirrors until it is solved, even if you enter your
password correctly.
If i logout in browser and login again by entering the CAPTCHA it is working fine. But if i host my application on server and if issue occurs, Logging out and login again is not the proper fix.
Can you please suggest good approach of handling this issue.
My Powershell code for Cloning the branch:
param(
[parameter(position=0)]
[string]$checkoutDirectory,
[parameter(position=1)]
[string]$checkoutBranch
)
function CheckoutTheCode($checkoutRepoUrl, $checkoutDirectory, $checkoutBranch)
{
[hashtable]$Return = #{}
try
{
if(Test-Path -Path $checkoutDirectory )
{
Remove-Item -Recurse -Force $checkoutDirectory
}
New-Item -ItemType directory -Path $checkoutDirectory
# Cloning
git clone --single-branch -b $checkoutBranch $checkoutRepoUrl $checkoutDirectory
$Return.Branch = $checkoutBranch
$Return.Directory = $checkoutDirectory
$Return.Status = $true
$Return.Message = "Success"
}
catch
{
$Return.Message = $Error[0].Exception
$Return.Status = $false
}
Return $Return
}
My Powershell code for Commit changes:
param(
[parameter(position=0)]
[string]$checkoutDirectory,
[parameter(position=1)]
[string]$commitMessage
)
function CommitTheCode($checkoutDirectory, $commitMessage)
{
[hashtable]$Return = #{}
try
{
cd $checkoutDirectory
git add .
git commit -m $commitMessage
git push
$Return.Status = $true
$Return.Message = "Success"
}
catch
{
$Return.Message = $Error[0].Exception
$Return.Status = $false
}
Return $Return
}
CommitTheCode $checkoutDirectory $commitMessage
The following steps worked for me (without asking a Bitbucket admin to click a button)
For Windows,
go to the credential manager (you can find this by searching for it in Start menu)
remove all credentials related to your bitbucket account
try again with your script.
Hi I am trying to create some sort of hybrid using power shell and c# as managing tool, so simple script in powershell that checks repo status
$git_status = git status
Write-Output $git_status
Now using Pipeline and Run
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(powershellScript);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder output = new StringBuilder();
foreach (PSObject obj in results)
{
output.AppendLine(obj.ToString());
}
return output.ToString();
}
But I am getting empty result, when I run script in IDE power shell result looks like for example:
Write-Host "$git_status"
On branch master Your branch is up-to-date with 'origin/master'. Changes to be committed:
(use "git reset HEAD ..." to unstage) modified: DeviceDatabase/Platforms.xml
What can i do to get that response back to c# procedure?
Write-Host will only print output to terminal, but it will not pass it to stdout. If you want to get the output - use Write-Output.
Write-Host is there to build UX: change output text color, etc. For anything else use Write-Output if you want to have your scripts as tools that can be combined to solve larger problems.
You can find a better explanation here. I'll use example code from the link to expand a little:
function Receive-Output
{
process
{
# catch input from pipe and print it in green
Write-Host $_ -ForegroundColor Green
}
}
# this will print green text, because it was passed to Receive-Output
Write-Output "this is a test" | Receive-Output
# this will print white text, because it was not passed to Receive-Output
# there's a good chance "this is a test" will already be printed by the time Receive-Output gets called
Write-Host "this is a test" | Receive-Output
Edit:
As git status prints a colorful text we can safely assume it's using Write-Host in PowerShell. Based on how Posh-Git reads git status into an object I've compiled a little example code that should solve your problem:
> $status = (git -c color.status=false status)
> Write-Output $status
This is the output I get (Windows 10, PowerShell Core 6.0):
I am executing a C# exe, CRS.exe, that I expect to return a non-zero value, such as -1. I am using ps to get the value back, and have this within a stage:
try{
pcode = (powershell(returnStdout: true, script: 'return Invoke-Expression -Command \" .\\perfmon\\CRS.exe hello \"'))''
echo "Pcode = ${pcode} "
}
catch (err) {echo err.message }
echo "Pcode = ${pcode} "
Based on this post, "Normally, a script which exits with a nonzero status code will cause the step to fail with an exception." --
Jenkins pipeline bubble up the shell exit code to fail the stage
I want to handle this non-zero result, is the exception handler the only way?
Results of above run:
Running PowerShell script
tester arg = hello
[Pipeline] echo
script returned exit code -1
[Pipeline] echo
Pcode = null
Interestingly enough, a char return seems to be fine? This returns without throwing an exception
icode = (powershell(returnStdout: true, script: 'return Invoke-Expression -Command \'.\\perfmon\\zipInstaller.ps1 -urlString ' + fileContents + "'"))
echo "icode = ${icode} "
Results in
[Pipeline] {
[Pipeline] powershell
[Chris] Running PowerShell script
[Pipeline] echo
icode = -5
I would like to catch the return codes from the exe's and manage my groovy pipelines flow based on that. Any insight would be greatly appreciated.
Instead of using returnStdout: true, try using returnStatus: true. It should always return the exit code. Not as helpful if you need the output from the powershell command all at once (without returnStdout, it will just print output to the Jenkins log), but as a workaround for that you could pipe output to a file and then print that out.
Another option (but it's ugly, so I don't recommend it) is to call Powershell from a bat command. bat should mask the error code for the powershell command, so Jenkins won't get excited and fail automatically, and you'll still get stdout. Obviously not too helpful if you actually wanted the error code though. Your line would look something like
pcode = (bat(returnStdout: true, script: 'Powershell.exe "return Invoke-Expression -Command \" .\\perfmon\\CRS.exe hello \"'"))
That line will need a bit of refining, but it might be another option.
I'm trying to decrypt a file using GPG, for which I use "Starksoft.Cryptography.OpenPGP". I'm getting the following error
Starksoft.Cryptography.OpenPGP.GnuPGException: An error occurred while trying to execute command --list-secret-keys.
But when I execute the command through command prompt ">gpg --list-secret-keys", it does list the keys. I could not get "Starksoft.Cryptography.OpenPGP" to work correctly.
Next I tried to get a solution by running the process directly using cmd.exe. None of the following commands is working however:
>echo gpg --passphrase Mypasspharse -o "C:\successtest.txt" -d "C:\testfile.txt.gpg"
>echo Mypasspharse|gpg.exe --passphrase-fd 0 -o "C:\successtest.txt" --decrypt "C:\testfile.txt.gpg"
>echo Mypasspharse|gpg --keyring "pubring.gpg location" --secret-keyring "secring.gpg location" --batch --yes --passphrase-fd 0 -o "C:\successtest.txt" -d "C:\testfile.txt.gpg"
>echo Mypasspharse|gpg -o C:\successtest.txt --batch --passphrase-fd 0 --decrypt C:\testfile.txt.gpg
>echo Mypasspharse|gpg2 --batch --passphrase-file "PrivateKey.asc location" --output C:\successtest.txt --decrypt C:\testfile.txt.gpg
Error Message : gpg: public key decryption failed: Bad passphrase
gpg: decryption failed: No secret key
Can anybody show me how to decrypt the file?
I figured out the issue with the gpg command line. The second command line worked just fine.
echo Mypasspharse|gpg.exe --passphrase-fd 0 -o "C:\successtest.txt" --decrypt "C:\testfile.txt.gpg"
Issue Was :
Mypassphare contained a character ">" which interpreted as std out redirect in windows command prompt. So, passphase wasn't passing to the next command properly.
Since this command worked properly, I didn't check on other syntax. Please feel free to check other commands and update here, if its wrong.
I have summarized the Q & A here: http://techsharehub.blogspot.com/2014/09/gpg-public-key-decryption-failed-bad.html