Custom VSTS Build Task to Call PhantomJS Fails to Create Image File - powershell

I am in the process of writing a custom VSTS extension that (based on parameters) requests a URL and emails the results. I have all pieces of it functioning properly, except the piece that calls PhantomJS exe. This is required in order to generate the screenshot, prior to attaching to the email.
The relevant PowerShell code is as follows:
Write-Verbose "Run phantomjs with $testingurl"
Start-Process -FilePath "phantomjs.exe" -ArgumentList "screenshot.js",$testingurl
$directory = Get-ScriptDirectory
Get-ChildItem $directory -force
I am calling PhantomJS with the relevant parameters, which should create an image in my working directory called 'example.png'. However, when I then output the contents of the directory, the file is not present.
I have played around with the "scope" of my extension, but it has not helped. My current scopes are:
"scopes": [
"vso.build_execute",
"vso.serviceendpoint_manage",
"vso.code_manage",
"vso.packaging_manage",
"vso.release_execute",
"vso.work_write"
],
I also verified that I can create a file if I use the standard PS commandlet:
New-Item "$directory\test.txt" -ItemType file
I also tried including a blank 'example.png' in my VSIX package that would hopefully be overwritten, but it does not.
So, I'm convinced it's not a write-permission issue. The VSTS logs give no indication of the call to PhantomJS exe failing.
Are you not allowed to call an exe from a PS script from within a VSTS extension (build task)? The PS script works correctly locally so I feel this is more of an environment/permission/allowance issue than a code issue on my part.

My issue ended up being that the exe was run and my code continued to execute. I had to add the "-Wait" attribute to my call:
Start-Process -FilePath "phantomjs.exe" -ArgumentList "screenshot.js",$testingurl -Wait
Since the lines following the call to phantomjs.exe requires the execution to finish, the "-Wait" ensures it runs to completion first.

Related

Powershell function call causes missing function error using powershell v7 on windows 10

I wrote a script to build all .net projects in a folder.
Issue
The issue is I am getting a missing function error when I call Build-Sollution.
What I tried
I made sure that function was declared before I used it so I am not really sure why it saids that it is not defined.
I am new to powershell but I would think a function calling another functions should work like this?
Thanks in advance!
Please see below for the error message and code.
Error Message
Line |
3 | Build-Sollution $_
| ~~~~~~~~~~~~~~~
The term 'Build-Sollution' 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.
Build-Sollution:
Code
param (
#[Parameter(Mandatory=$true)][string]$plugin_path,
[string]$depth = 5
)
$plugin_path = 'path/to/sollutions/'
function Get-Sollutions {
Get-ChildItem -File -Path $plugin_path -Include *.sln -Recurse
}
function Build-Sollution($solution) {
dotnet build $solution.fullname
}
function Build-Sollutions($solutions) {
$solutions | ForEach-Object -Parallel {
Build-Sollution $_
}
}
$solutions_temp = Get-Sollutions
Build-Sollutions $solutions_temp
From PowerShell ForEach-Object Parallel Feature | PowerShell
Script blocks run in a context called a PowerShell runspace. The runspace context contains all of the defined variables, functions and loaded modules.
...
And each runspace must load whatever module is needed and have any variable be explicitly passed in from the calling script.
So in this case, the easiest solution is to define Build-Sollution inside Build-Sollutions
As for this...
I am new to powershell but I would think a function calling another
functions should work like this?
... you cannot use the functions until you load your code into memory. You need to run the code before the functions are available.
If you are in the ISE or VSCode, if the script is not saved, Select All and hit use the key to run. In the ISE use F8 Selected, F5 run all. In VSCode, F8 run selected, crtl+F5 run all. YOu can just click the menu options as well.
If you are doing this from the consolehost, the run the script using dot sourcing.
. .\UncToYourScript.ps1
It's ok to be new, we all started somewhere, but it's vital that you get ramped up first. so, beyond what I address here, be sure to spend time on Youtube and search for Beginning, Intermediate, Advanced PowerShell for videos to consume. There are tons of free training resources all over the web and using the built-in help files would have given you the answer as well.
about_Scripts
SCRIPT SCOPE AND DOT SOURCING Each script runs in its own scope. The
functions, variables, aliases, and drives that are created in the
script exist only in the script scope. You cannot access these items
or their values in the scope in which the script runs.
To run a script in a different scope, you can specify a scope, such as
Global or Local, or you can dot source the script.
The dot sourcing feature lets you run a script in the current scope
instead of in the script scope. When you run a script that is dot
sourced, the commands in the script run as though you had typed them
at the command prompt. The functions, variables, aliases, and drives
that the script creates are created in the scope in which you are
working. After the script runs, you can use the created items and
access their values in your session.
To dot source a script, type a dot (.) and a space before the script
path.
See also:
'powershell .net projects build run scripts'
'powershell build all .net projects in a folder'
Simple build script using Power Shell
Update
As per your comments below:
Sure the script should be saved, using whatever editor you choose.
The ISE does not use PSv7 by design, it uses WPSv5x and earlier.
The editor for PSv7 is VSCode. If you run a function that contains another function, you have explicitly loaded everything in that call, and as such it's available.
However, you are saying, you are using PSv7, so, you need to run your code in the PSv7 consolehost or VSCode, not the ISE.
Windows PowerShell (powershell.exe and powershell_ise.exe) and PowerShell Core (pwsh.exe) are two different environments, with two different executables, designed to run side-by-side on Windows, but you do have to explicitly choose which to use or write your code to branch to a code segment to execute relative to the host you started.
For example, let's say I wanted to run a console command and I am in the ISE, but I need to run that in Pwsh. I use a function like this that I have in a custom module autoloaded via my PowerShell profiles:
# Call code by console executable
Function Start-ConsoleCommand
{
[CmdletBinding(SupportsShouldProcess)]
[Alias('scc')]
Param
(
[string]$ConsoleCommand,
[switch]$PoSHCore
)
If ($PoSHCore)
{Start-Process pwsh -ArgumentList "-NoExit","-Command &{ $ConsoleCommand }" -PassThru -Wait}
Else {Start-Process powershell -ArgumentList "-NoExit","-Command &{ $ConsoleCommand }" -PassThru -Wait}
}
All this code is doing is taking whatever command I send it and if I use the PoSHCore switch...
scc -ConsoleCommand 'SomeCommand' -PoSHCore
... it will shell out to PSCore, run the code, otherwise, it just runs from the ISE>
If you want to use the ISE with PSv7 adn not do the shell out thing, you need to force the ISE to use PSv7 to run code. See:
Using PowerShell Core 6 and 7 in the Windows PowerShell ISE

Invoking long NAnt process from PowerShell form Jenkins (using Pipelines)

I've been working on wrapping up the usage of some old NAnt scripts behind a Jenkins job. The Jenkins job itself is using the pipelines feature, a groovy DSL script, one of the steps is a PowerShell block, and it calls some a function that invokes NAnt, after working out lots of parameters to be parsed in.
I did have this working at some point just fine, but something has broken at some stage. The PowerShell function is called, and it triggers NAnt, and for the nearly an hour that it takes to complete, you get the output, as it happens, showing up in Jenkins.
This was done using something like Invoke-Expression "& $NAntExe $NAntFile $Target $ParameterString" | Write-Host, where $ParameterString is all the -D:Key=Value parameters.
I believe I had added the | Write-Host as without it, you only get the output at the very end, but we wanted to be able to see the progress as it's happening.
As I said, something has changed somewhere, and we were no longer getting any output from NAnt. I eventually found that removing the | Write-Host would restore the logs, but as I expected, we now have to wait for NAnt to finish before we see any logs.
What is the 'correct' way to invoke NAnt here to get the output as I desire? I want to see the output as it happens.
I've tried various ways of invoking NAnt, with no luck. Seems I'm having to settle for either "I get all the output in one go at the end" or "no output". I suspect this is not a PowerShell issue as such, but that's based on nothing but gut feeling.
Seems I can mostly recreate the symptoms I see in Jenkins. If I invoke NAnt through a fresh PowerShell session I get the same problem, I'm running something akin the following, which as far as I can tell would be the same as how the Jenkins plugin invokes PowerShell:
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy ByPass -Command 'Invoke-FunctionThatCallsNAnt'
Within my Invoke-FunctionThatCallsNAnt, I had initially, as I said above, just directly called NAnt and got no logging. I then update my function to pipe the output to Write-Host or I can remove the -NonInteractive flag and I will get the output from NAnt in real time. However, when I go to Jenkins, this does not resolve the problem, I end up with getting no output at all.
I'm not sure why it wouldn't stream. You should be able to write the command these ways:
& $NAntExe $NAntFile $Target $ParameterString
Or with whatever the nant command is.
$env:path += ';c:\program files\nant' # add to path if needed
nant.exe $NAntFile $Target $ParameterString
If it's not in the path, and the folder doesn't have spaces, you can put the whole path to it as well.
c:\nant\nant.exe $NAntFile $Target $ParameterString
EDIT:
Here's a way to run something in a path with spaces:
C:\Program` Files\Internet` Explorer\iexplore.exe
EDIT2:
It looks like you have to unblock the nant zip after downloading it: How do I resolve configuration errors with Nant 0.91?
Or unblock all the files after the fact:
get-childitem -recurse c:\nant-92 |
get-item -stream zone.identifier -erroraction silentlycontinue |
select -expand filename | get-item | unblock-file

Get-Content with wait parameter doesn't update in Powershell

I'm trying to monitor a file using Get-Content $path -wait in Windows Powershell V3.0. Sometimes when I execute this command line in Powershell it will function as expected. But sometimes it will only execute (or at least it seems like) get-content but without the -wait parameter. Even though the file get's updated it won't be shown in Powershell. If I cancel the command and rerun it it will show the updated file content.
What do I need to do?
EDIT: It seems to update blocks after a while. But it's not real-time really.
Not allowed to comment (don't have a 50 reputation), so have to give an Answer....
Less for Windows (http://gnuwin32.sourceforge.net/packages/less.htm) with the +F or Shift-F option (http://www.commandlinefu.com/commands/view/1024/make-less-behave-like-tail-f.) showed updated file content where PowerShell "get-content $path -wait" did not.

How to get command prompt's output into a variable with PowerShell

I'm using PowerShell v3.0 to start a new cmd.exe process, in which I then load up the Visual Studio Command Prompt to perform a build, like so:
Start-Process cmd.exe -ArgumentList $cmdArgumentsToRunMsBuildInVsCommandPrompt -WindowStyle $windowStyle -Wait
This works, and it opens a new command prompt window and I can see the build happen, and then when the build is finished the command prompt window closes. I would like to be able to get the text that is written to the command prompt window and store it in a variable, in order to inspect if the build passed or not. I tried using this, but it doesn't work; the $buildOutput variable is empty:
Start-Process cmd.exe -ArgumentList $cmdArgumentsToRunMsBuildInVsCommandPrompt -WindowStyle $windowStyle -Wait -OutVariable buildOutput
Write-Host "Build output = $buildOutput"
This makes sense since the cmd.exe process isn't returning any text; it is just writing it to it's own window. Is there a way for me to be able to store that text in a variable for the original powershell script to use? I know that I can provide a parameter to MsBuild to have it write the build log to a file, but I'm looking for a solution that doesn't involve writing to a log file and having to delete it later.
Any suggestions are appreciated. Thanks!
<# EDIT #>
Thanks for all of the responses so far! A popular suggestion has been to just call MsBuild.exe directly without using cmd.exe. The reason I need to go through cmd.exe is some projects don't build successfully if called directly from MsBuild.exe (e.g. XNA projects). Instead I need to call MsBuild.exe from the Visual Studio Command Prompt so that (I assume) all of the required environmental variables are set. I guess I could just call the VS Command Prompt directly, but it will have the same problem as calling cmd.exe too. If I can't find the VS Command Prompt I fallback to calling MsBuild.exe directly, so those answers are still appreciated.
You can always capture the output of console programs this way:
$output = [string](nuget.exe)
Here I used nuget ($output will contain the available commands list), but you can of course use msbuild.exe with the appropriate arguments.
I've solved my problem using a suggestion from the first comment on my question, which was to write the build output to a log file, consume it, then delete it. This allows me to still show the user the cmd window with the build progress if they need, as well inspect the build output once the build completes. It also still allows me to run the build in another process, so we can use PassThru if we don't want our script to wait for the build to complete before continuing execution.
I've created an Invoke-MsBuild powershell module to make building with MsBuild a snap while providing lots of parameters for additional functionality (returns if build succeeded or failed, can show/hide build window, can wait/not wait for build to finish, can automatically show build log on failed builds, etc.). You can view and download the script from my blog.
$process = New-Object System.Diagnostics.Process;
$process.StartInfo.UseShellExecute = $false;
$process.StartInfo.RedirectStandardOutput = $true;
$process.StartInfo.FileName = "cmd.exe";
$process.StartInfo.Arguments = $cmdArgumentsToRunMsBuildInVsCommandPrompt;
$process.Start();
$outputStream = $process.StandardOutput;
$outputStream.ReadToEnd();
You could also redirect StandardError.
edit: I ended up using #David Brabant's answer
I ran into this problem and created an echo function
function echo()
{
$input
}
which let me do this
$output = &"cmd.exe" $args | echo

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