deploying a zip file with maven - powershell

I am trying to deploy a zip file to nexus using deploy:deploy-file but maven still not happy about this and is complaining about a missing project/pom file. Below is the code snippet and debug log
$params =
#(
"deploy:deploy-file",
"-X",
"-e",
"-DartifactId=${env:ZIP_PREFIX}",
"-Dmaven.wagon.provider.http=httpclient",
"-Durl=http://abc-nexus.repo.net:9081/repository/releases-prod-dist",
"-DrepositoryId=releases-prod-dist",
"-DgroupId=$nexusPath",
"-Dversion=$fullVersion",
"-Dpackaging=zip",
"-Dfile=$reviewArea\$zipName"
)
Start-Process "java" -ArgumentList #("-version") -Wait -NoNewWindow
Start-Process "mvn" -ArgumentList #("-version") -Wait -NoNewWindow
Write-Output "Start-Process mvn -NoNewWindow -Wait -ArgumentList ${params}"
Start-Process mvn -NoNewWindow -PassThru -Wait -ArgumentList $params
2020-09-11T06:17:27.7943241Z [INFO] Scanning for projects...
2020-09-11T06:17:27.9140863Z [DEBUG] Extension realms for project org.apache.maven:standalone-pom:pom:1: (none)
2020-09-11T06:17:27.9466573Z [DEBUG] Looking up lifecycle mappings for
packaging pom from ClassRealm[plexus.core, parent: null]
2020-09-11T06:17:27.9641628Z [INFO] ------------------------------------------------------------------------
2020-09-11T06:17:27.9643764Z [INFO] BUILD FAILURE
2020-09-11T06:17:27.9645595Z [INFO] ------------------------------------------------------------------------
2020-09-11T06:17:27.9684029Z [INFO] Total time: 0.250 s
2020-09-11T06:17:27.9689684Z [INFO] Finished at: 2020-09-10T23:17:27-07:00
2020-09-11T06:17:28.0604956Z [INFO] Final Memory: 6M/245M
2020-09-11T06:17:28.0608153Z [INFO] ------------------------------------------------------------------------
2020-09-11T06:17:28.0695335Z [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (C:\AzureRemoteAgent\_work\r16\a). Please verify you invoked Maven from the correct directory. -> [Help 1]
2020-09-11T06:17:28.0700315Z org.apache.maven.lifecycle.MissingProjectException: The goal you specified requires a project to execute but there is no POM in this directory (C:\AzureRemoteAgent\_work\r16\a). Please verify you invoked Maven from the correct directory.
2020-09-11T06:17:28.0703641Z at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:85)
2020-09-11T06:17:28.0708399Z at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:309)
2020-09-11T06:17:28.0710747Z at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:194)
2020-09-11T06:17:28.0712639Z at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:107)
2020-09-11T06:17:28.0714330Z at org.apache.maven.cli.MavenCli.execute (MavenCli.java:955)
2020-09-11T06:17:28.0716002Z at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:290)
2020-09-11T06:17:28.0717718Z at org.apache.maven.cli.MavenCli.main (MavenCli.java:194)
2020-09-11T06:17:28.0719285Z at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
2020-09-11T06:17:28.0721040Z at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
2020-09-11T06:17:28.0723365Z at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
2020-09-11T06:17:28.0725220Z at java.lang.reflect.Method.invoke (Method.java:498)
2020-09-11T06:17:28.0727008Z at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
2020-09-11T06:17:28.0729074Z at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
2020-09-11T06:17:28.0731080Z at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
2020-09-11T06:17:28.0733229Z at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)

Atleast in Powershell, every argument needs to be enclosed in double quotes. I ended up doing single quotes around arguments that don't have variables and backticks around the ones that do. This preserves the double quotes in arguments and variables are expanded.
$params =
#(
'"deploy:deploy-file"',
'"-X"',
'"-e"',
"`"-DartifactId=${env:ZIP_PREFIX}`"",
'"-Dmaven.wagon.provider.http=httpclient"',
'"-Durl=http://abc-nexus.repo.net:9081/repository/releases-prod-dist"',
'"-DrepositoryId=releases-prod-dist"',
"`"-DgroupId=$nexusPath`"",
"`"-Dversion=$fullVersion`"",
'"-Dpackaging=zip"',
"`"-Dfile=$parentDir\$zipName`""
)

Related

Pester 5 test no longer working with Start-Job

This was working before Pester 5.3.0 but now it seems broken and I do not know why it has stopped working. The idea of this tests is to check to see if counters have been removed, this is part of a larger installation and uninstallation. But the problem is the counter remain in the current powershell process. This needs to start a new PS so it will run the tests and return the results and then post them in the automation. I added the error that I am now receiving.
I tried to rename the tests to counters.Test.ps1 but that didn't seem work. So I am kind of at a loss at this point. Any help would be great, thanks in advance out there.
The actual test is really basic and runs just fine outside of a job.
Results:
Pester v5.3.0
System.Management.Automation.RuntimeException: No test files were found and no scriptblocks were provided. Please ensure that you provided at least one path to a *.Tests.ps1 file, or a directory that contains such file. Or that you provided a ScriptBlock test container.
at Invoke-Pester<End>, C:\Users\Administrator\Documents\PowerShell\Modules\Pester\5.3.0\Pester.psm1: line 5220
at <ScriptBlock>, <No file>: line 6
$TestFiles = #(
".\pestertests\test_new_counters.ps1",
".\pestertests\test_counters.test.ps1"
)
foreach ($file in $TestFiles[1]){
$newPSSession = {
function Get-Counters {
Start-Process pwsh
}
}
$mainScript = {
Param (
$scriptPath
)
$container = New-PesterContainer -Path $scriptPath
Invoke-Pester -Container $container -Output Diagnostic -PassThru
}
$job = Start-Job -Name UninstallCounterCheck -InitializationScript $newPSSession -ScriptBlock $mainScript -ArgumentList $file
$results = $job | Receive-Job -Wait -AutoRemoveJob
}

Register-Scheduledjob creates a job but it never runs at startup

I have tried 100 ways to register-scheduledjob to run a script that would start the program.
nothing seems to be working consistently.
my last attempt was using Register-ScheduledTask, this one does create the job but doesn't start it automatically at system startup. the funny thing is if I run it manually once, it would start on its own on future restarts. but if I wanted to run it once myself there is no point in scheduling the job!
this is what I am doing:
$description = "Scheduling job using Tasks"
$taskPath = "\Microsoft\Windows\PowerShell\ScheduledJobs\"
$argument = "'Register-ScheduledJob -Name "+$scheduledJobName+" -Trigger "+$trigger+" -FilePath "+$TaskParametersPath+" -ScheduledJobOption "+$option+" -Credential "+$cred+" -RunAs32 2>&1'"
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument $argument
$taskTriger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:30
$job = Register-ScheduledTask -Action $action -Trigger $taskTriger -TaskName $scheduledJobName -Description $description -TaskPath $taskPath
the original code I had was:
$job = Register-ScheduledJob -Name $scheduledJobName -Trigger $trigger -FilePath $TaskParametersPath -ScheduledJobOption $option -Credential $cred -RunAs32 2>&1
I also tried this one:
$job = Register-ScheduledJob -Name $scheduledJobName -Trigger $trigger -FilePath $TaskParametersPath -ScheduledJobOption $option -Credential $cred -Authentication Credssp 2>&1
with trigger and option:
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30
$option = New-ScheduledJobOption -RunElevated
$taskParametersPath is a powershell script that starts another powershell script and passes all the required parameters for it.
all of this works occasionally, but sometimes it fails to schedule the job with the error I have here. it works all the time when I am logged into the machine and try to register the job, but it fails occasionally when I run it as a part of VM creation script using azure stack templates. :(
this is the error I get:
ERROR : FullyQualifiedErrorId : CantRegisterScheduledJobDefinition,Microsoft.PowerShell.ScheduledJob.RegisterScheduledJobCommand
2018/06/01 23:41:47 : ERROR : Exception:Microsoft.PowerShell.ScheduledJob.ScheduledJobException: An error occurred while registering scheduled job definition VaaSRestartTask to the Windows Task Scheduler. The Task Scheduler error is: The user name or password is incorrect. (Exception from HRESULT: 0x8007052E). ---> System.Runtime.InteropServices.COMException: The user name or password is incorrect. (Exception from HRESULT: 0x8007052E)
at TaskScheduler.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, _TASK_LOGON_TYPE LogonType, Object sddl)
at Microsoft.PowerShell.ScheduledJob.ScheduledJobWTS.CreateTask(ScheduledJobDefinition definition)
at Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition.AddToWTS()
at Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition.Register()
--- End of inner exception stack trace ---
at Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition.Register()
at Microsoft.PowerShell.ScheduledJob.RegisterScheduledJobCommand.ProcessRecord()
2018/06/01 23:41:47 : ERROR : Category:InvalidOperation: (Microsoft.Power...edJobDefinition:ScheduledJobDefinition) [Register-ScheduledJob], ScheduledJobException

Powershell script can't execute Register-ScheduledJob as a Azure Resource Manager CustomScriptExtension

I have an deployment template for an azure virtual machine scale with this extensionProfile:
"extensionProfile": {
"extensions": [
{
"name": "customScript",
"location": "[resourceGroup().location]",
"properties": {
"publisher": "Microsoft.Compute",
"type": "CustomScriptExtension",
"settings": {
"fileUris": [
"[concat(parameters('customInstallScriptLocation'), parameters('customInstallScriptFileName'))]"
]
},
"typeHandlerVersion": "1.8",
"autoUpgradeMinorVersion": true,
"protectedSettings": {
"commandToExecute": "[concat('powershell -ExecutionPolicy Unrestricted -File \"', parameters('customInstallScriptFileName'), '\" -adminUsername ', parameters('adminUsername'), ' -adminPassword ', parameters('adminPassword'))]"
}
}
}
]
}
When deploying the vmss the custom script is executed, commands like Invoke-WebRequest and Start-Process work without a problem. But Register-ScheduledJob doesn't work. When I connect to the remote desktop and run this install script manually everything works properly.
This is the code that fails when not running it manually:
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:45
Register-ScheduledJob -Trigger $trigger -FilePath $installDir\natPuncherStartupScript.ps1 -Name NPSSOnStartup >> $log
logAndClearErrors $true
The error is:
Register-ScheduledJob : An error occurred while registering scheduled jobdefinition NPSSOnInstall to the Windows Task Scheduler. The Task Scheduler error is: (32,4):UserId:.
I also tried:
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:45
Register-ScheduledJob -Credential $credential -Trigger $trigger -FilePath $installDir\natPuncherStartupScript.ps1 -Name NPSSOnStartup >> $log
logAndClearErrors $true
But now an error shows that the username/password is invalid. Also when running this manually from remote desktop this works fine.
What am I missing? Why can't I schedule a job from a customscriptextension?
You need to have it login as LocalSystem account if you want to have the vmextension register it.
Register-ScheduledTask -TaskName $jobname -Action $action -Trigger $trigger -RunLevel Highest -User "System" -Settings $settings
Stackoverflow link of this issue I had
According to your description, I could reproduce the errors you encountered by using Register-ScheduledJob.
From the official document about Register-ScheduledJob.
-Credential
Specifies a user account that has permission to run the scheduled job. The default is the current user.
I assumed that this issue is possibly casued by the user account that runs this scheduled job. After some trials, it could work as expected on my side and the scheduled job could be registered to my Azure VM by using ARM template. Here is the core command, you could refer to it.
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:45
$pwd= ConvertTo-SecureString “{your-vm-adminPwd}” -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential (“{your-vm-adminName}”, $pwd)
Register-ScheduledJob -Trigger $trigger -FilePath $installDir\start1.ps1 -Name bruceScheduledJob -Credential $credential -Authentication CredSSP
I spent HOURS with the same problem and did not want to provide User/Password info in the script and other solutions failed. This PowerScript line finally worked (executes the batch command YourCommand):
&schtasks /create /tn YourTaskName /sc onstart /tr YourCommand /NP /DELAY 0001:00 /RU SYSTEM

Inject command line arguments into psake

I would like to inject command line parameters into my psake build script like:
.\build.ps1 Deploy environment="development"
But psake will treat every argument as a Task and will answer "task does not exists"
Is it possible to inject command line arguments in psake?
build.ps1 -->
Import-Module '.\psake.psm1'
Invoke-psake '.\tasks.ps1' $args
Remove-Module psake
The latest release of psake now supports passing parameters to Invoke-psake, e.g.
Invoke-psake .\parameters.ps1 -parameters #{"p1"="v1";"p2"="v2"}
This feature has just been added. :)
A global variable will solve my problem for now and with only one reference to $global:arg_environent it will be easy to change if i find a better way to inject the properties.
build.ps1
param(
[Parameter(Position=0,Mandatory=0)]
[string]$task,
[Parameter(Position=1,Mandatory=0)]
[string]$environment = 'dev'
)
clear
$global:arg_environent = $environment
Import-Module .\psake.psm1
Invoke-psake tasks.ps1 $task
Remove-Module psake
tasks.ps1
properties {
$environment = $global:arg_environent
}
task default -depends Deploy
task Deploy {
echo "Copy stuff to $environment"
}
I'm no expert, but I don't think it is possible to pass arguments to Invoke-Psake. Looking on the latest source for Psake the params for the Invoke-Psake function are:
param(
[Parameter(Position=0,Mandatory=0)]
[string]$buildFile = 'default.ps1',
[Parameter(Position=1,Mandatory=0)]
[string[]]$taskList = #(),
[Parameter(Position=2,Mandatory=0)]
[string]$framework = '3.5',
[Parameter(Position=3,Mandatory=0)]
[switch]$docs = $false
)
There are 4 parameters, your build file, a list of tasks, the .NET framework version, whether to output docs of your tasks. I'm new to powershell and psake and I'm trying to do the same thing, I am experimenting with doing something like this in my script to achieve the same thing:
properties {
$environment = "default"
}
task PublishForLive -precondition { $environment = "Live"; return $true; } -depends Publish {
}
task PublishForStaging -precondition { $environment = "Staging"; return $true; } -depends Publish {
}
task Publish {
Write-Host "Building and publishing for $environment environment"
#Publish the project...
}
Then calling psake with PublishForLive or PublishForStaging, whichever I need:
powershell -NoExit -ExecutionPolicy Unrestricted -Command "& {Import-Module .\tools\psake\psake.psm1; Invoke-psake .\psake-common.ps1 PublishForLive }"
But it doesn't seem to work for me! Setting the $environment variable in the task precondition seems to have no effect. Still trying to make this work...

Determine If Solution Compiles using MSBuild and PSake

I have put together a PSake (v2.0) build script, and the script is setting the $psake.build_success property as true even thought the call to MSBuild fails. Can anyone advise me on how to alter the script so that the $psake.build_success property will correctly return false when the MSBuild call fails?
My PSake build script is as follows:
properties {
$solutionFile = 'SOLUTION_FILE'
$buildSuccessfulMessage = 'Solution Successfully Built!'
$buildFailureMessage = 'Solution Failed to Build!'
$cleanMessage = 'Executed Clean!'
}
task default -depends BuildSolution
task BuildSolution
{
msbuild $solutionFile /t:Clean,Build
if ($psake.build_success)
{
$buildSuccessfulMessage
}
else
{
$buildFailureMessage
}
}
Is PowerShell's native $lastExitCode (i.e., WIn32 ExitCode) any use in the context? I'd be guessing that the built in one is only relevant when you're invoking a psake-related cmdlet.
i.e., replace the check with
if($lastexitcode -eq 0) {
Disclaimer: Only podcast level experience with psake :D
The issue seems to be that the call to MSBuild operation actually completes successfully, whilst the build operation it initiates fails. The way I was able to get around this was to pipe the output of the MSBuild call to a text file, and then parse the file for the string "Build Failed". If it contained the string, obviously the build failed.
My PSake build script is as follows:
properties {
$solutionFile = 'SOLUTION_FILE'
$buildSuccessfulMessage = 'Solution Successfully Built!'
$buildFailureMessage = 'Solution Failed to Build!'
$cleanMessage = 'Executed Clean!'
}
task default -depends Build
task Build -depends Clean {
msbuild $solutionFile /t:Build /p:Configuration=Release >"MSBuildOutput.txt"
}
task Clean {
msbuild $solutionFile /t:Clean
}
and in my calling script:
function Check-BuildSuccess()
{
return (! (Find-StringInTextFile -filePath .\MSBuildOutput.txt -searchTerm "Build Failed"))
}
function Is-StringInTextFile
(
[string]$filePath = $(Throw "File Path Required!"),
[string]$searchTerm = $(Throw "Search Term Required!")
)
{
$fileContent = Get-Content $filePath
return ($fileContent -match $searchTerm)
}
There is the psake Exec command that you can wrap msbuild with and a powershell error is thrown.
Exec {
msbuild $solutionFile "/p:Configuration=$buildConfiguration;Platform=$buildPlatform;OutDir=$tempOutputDirectory"
}
Neither $LastExitCode or $_ worked for me. This did however:
$buildArgs = "MySolution.sln", "/t:Build", "/p:Configuration=Debug"
$procExitCode = 0
$process = Start-Process -FilePath "msbuild" -ArgumentList $buildArgs -NoNewWindow -PassThru
Wait-Process -InputObject $process
$procExitCode = $process.ExitCode
#aha! msbuild sets the process exit code but powershell doesn't notice
if ($procExitCode -ne 0)
{
throw "msbuild failed with exit code $procExitCode."
}
P.S. If you use this in production I recommend adding -timeout handling to Wait-Process