Verbose preference does not work - psake

I would like to use the Verbose preference ($VerbosePreference) inside my build script. I'm using the Chocolatey version of psake (so calling the batch file) and I cannot get it to work well at all.
The -Verbose switch works not at all. I ended up adding a property and pass that in. It gets passed in and then I set the $VerbosePreference to 'Continue' if it is true, otherwise 'SilentlyContinue'. I created a function to do this. In that function, if I call Write-Verbose, it works. However in a task, it does not. If I set the $VerbosePreference in the task, it does not work. Basically, I can't use Write-Verbose in tasks. What concept am I missing here? Completely flumoxed...

Related

Add_Click function from XAML only parses some commands?

This is an extremely strange issue- I have some Powershell code and a XAML GUI I made with Visual Studio for a fairly basic app for users. I'm fairly experienced with Powershell, but completely new to XAML.
Here's the code snippet:
`
$var_RKH.Add_Click({
$targetSite = $RKH
$var_TargetSite.Content = "Rock Hill"
})
`
Somehow, $targetSite is still null after this click event. I've confirmed the var $RKH contains the needed data. In another click event on another button, I copy-pasted that same line and it works. However, what's absolutely twisted my brain is- the third line works. The $var_TargetSite.Content variable is correctly updated.
So the click event is definitely firing, the second line just gets completely skipped somehow, and the third line works fine. On other click events, the exact same code works fine. I must be missing something very simple because this is absolutely twisting my brain.
Script blocks aren't really scopes. They're script blocks and do not inherit from enclosing scope. Instead, you pass values into it just like you would for a thread in C#. This can get confusing because both scopes and script blocks get the {} delimiter -- they're not the same though and not interchangeable either:
[scriptblock]$Sb = {'This is a test'}
if($true) $sb
will throw a ParserError exception rather than print 'this is a test'.
Please be very careful about "sideloading" variables, especially with WPF; there is a high degree of multithread in any WPF application and you literally don't know who is going to access what when.
If you can, try to resolve the value of $RKH inside the script block rather than try to force it in.
Or you could implement code-behind for the XAML and put both .xaml and .xaml.cs in an assembly, then use that in PS.

Powershell script “on exit” event?

Instead of calling a function at the end of all scripts to perform cleanup tasks, I'm looking to register for an 'on return' event for when the script (not the PowerShell session) is finished.
A script can return at various points though (eg, no records to process), so the current situation is problematic.
Register-EngineEvent applies to the PowerShell session, and operators run scripts manually, thus it's problematic.
I can't find a list of built-in powershell events or an alternative solution.
#Vesper wrote it as a comment, but a try/finally block is definitely what I would suggest for this:
try {
# some code
} finally {
# this gets executed even if the code in the try block throws an exception
}

PowerShell wait for function call to complete

I am calling a series of PowerShell functions from a master script (each function is a test).
I specify the tests in an XML file and I want them to run in order.
The functions to call are organized in PowerShell module files (.psm1). The master script calls Import-Module as needed and then calls the function via something like this...
$newResults = & "$runFunction" #ARGS
or this...
$newResults = Invoke-Expression $runFunctionWithArgs
I have gotten both to work just fine and the XML file parsing invokes these commands in the correct order.
Problem: The tests are apparently launched asynchronously so that the first test I launch does not necessarily get invoked and complete before the second test is invoked.
Note, the tests are functions in a PowerShell module and not commands so I do not think that Start-Process will work (but please tell me if you know how to make that work).
More Details:
It would take too much to add all the code, but essentially what each function call does is create a hashtable with one or more "TestResult" objects. "TestResult" has things like Success codes and a TimeStamp. Each test does things that take different amounts of time, but all synchronous. I would expect the timestamps to be the same order that I called each test, especially since the first thing each test does is get the timestamp so it should not depend on what the test does. When I run in the ISE, everything goes in order. When I run in the command window, the timestamps do not match my expected order.
Workaround:
My working theory is still that PowerShell is somehow parallelizing the calls. I can get consistent results by making the invocation of each call dependent on the results of the previous call. It is a dummy check because I know that what I test will always be true, but PowerShell doesn't know that
if ($newResults.Count -ne [Long]::MaxValue) { $newResults = & "$runFunction" #ARGS }
PowerShell thinks that it needs to know if the previous call count is not MaxValue.

Hosting PowerShell: PowerShell vs. Runspace vs. RunspacePool vs. Pipeline

I attempting to add some fairly limited PowerShell support in my application: I want the ability to periodically run a user-defined PowerShell script and show any output and (eventually) be able to handle progress notification and user-prompt requests. I don't need command-line-style interactive support, or (I think) remote access or the ability to run multiple simultaneous scripts, unless the user script does that itself from within the shell I host. I'll eventually want to run the script asynchronously or on a background thread, and probably seed the shell with some initial variables and maybe a cmdlet but that's as "fancy" as this feature is likely to get.
I've been reading the MSDN documentation about writing host application code, but while it happily explains how to create a PowerShell object, or Runspace, or RunspacePool, or Pipeline, there's no indication about why one would choose any of these approaches over another.
I think I'm down to one of these two, but I've like some feedback about which approach is a better one to take:
PowerShell shell = PowerShell.Create();
shell.AddCommand(/* set initial state here? */);
shell.AddStatement();
shell.AddScript(myScript);
shell.Invoke(/* can set host! */);
or:
Runspace runspace = RunspaceFactory.CreateRunspace(/* can set host and initial state! */);
PowerShell shell = PowerShell.Create();
shell.Runspace = runspace;
shell.AddScript(myScript);
shell.Invoke(/* can set host here, too! */);
(One of the required PSHost-derived class methods is EnterNestedPrompt(), and I don't know whether the user-defined script I run could cause that to get called or not. If it can, then I'll be responsible for "starting a new nested input loop" (as per here)... if that impacts which path to take above, that would also be good to know.)
Thanks!
What are they?
Pipeline
A Pipeline is a way to concatenate commands inside a powershell script. Example: You "pipe" the output from Get-ChildeItem to Where-Object with | to filter them:
Get-ChildItem | Where-Object {$_}
PowerShell Object
The PowerShell object referes to a powershell session, like the one you would get when you start powershell.exe.
Runspace
Every powershell session has its own runspace (You'll always get output from Get-Runspace). It defines the state of the powershell session. Hence the InitialSessionState object/property of a runspace. You may decide to create a new powershell session, with its own runspace from within a powershell, to enable a kind of multithreading.
RunspacePool
Last but not least the RunspacePool. Like the name says, it's a pool of runspaces (or powershell sessions) that can be used to process a lot of complecated tasks. As soon as one of the runspaces in the pool has finished its task it may take the next task till everything is done. (100 things to do with 10 runspaces: on avarage they process 10 each but one may process 8 while two others process 11...)
When to use what?
Pipeline
The pipeline is used insed of scripts. It makes it easier to build complex scripts and should be used as often as possible.
PowerShell Object
The powershell object is used when ever you need a new powershell session. You can create one inside of an existing script, be it C# or Powershell. It's usefull for easy multithreading. On its own it will create a default session.
Runspace
If you want to create a non standard session of powershell, you can manipulate the runspace object before you create a powershell session with it. It's usefull when you want to share synchronized variables, functions or classes in the extra runspaces. Slightly more complex multithreading.
RunspacePool
Like mentioned before it's a heavy tool for heavy work. When one execution of a script takes hours and you need to do it very often.E.g. In combination with remoting you could simultanly install something on every node of a big cluster and the like.
You are overthinking it. The code you show in samples is a good start. Now you just need to read the result of Invoke() and check the error and warning streams.
PowerShell host provides some hooks that RunSpace can use to communicate with user, like stream and format outputs, show progress, report errors, etc. For what you want to do you do not need PowerShell Host. You can read results back from script execution using PowerShell class, check for errors, warnings, read output streams and show notification to the user using facilities of your application. This will be much more straightforward and effective than write entire PowerShell host to show a message box if errors detected.
Also, PowerShell object HAS a Runspace when it is created, you do not need to give it one. If you need to retain the runspace to preserve the environment just keep entire PowerShell object and clear Commands and all Streams each time after you call Invoke.
The next question you should ask is how to process result of PowerShell::Invoke() and read PowerShell::Streams.

PowerShell: Can you hook or intercept PowerShell execution of external applications?

I want to do some housekeeping before executing any external console applications (setting some environment vars).
In my web research, it looks like overriding NotifyBeginApplication() in $host might do the trick. Unfortunately, I can't figure out how to do that.
Here's essentially what I want to do...
$host = $host | `
Add-Member -force -pass -mem scriptmethod NotifyBeginApplication `
{ $env:_startTime = [datetime]::now; $env:_line = $myInvocation.Line }
This doesn't work as $host is constant and it may be the wrong approach anyway.
The documentation that I've been able to find states that this function is called before any "legacy" console application is executed, but another blog entry says that it's only called for console applications that have no I/O redirection.
So, is this the right way to do this? If so, how would I override the function?
If not, how could this be done?
The only alternative I've seen that might work is to fully implement a custom PSHost. That seems possible with existing available source code, but beyond what I want to attempt.
If this is code that you can modify, then create this function:
Function call {
## Set environment here
$env:FOO = "BAR"
Invoke-Expression "$args"
}
Now pass your native commands to the call function. Examples:
call cmd /c set
call cmd /c dir
call somefunkyexe /blah -ooo aaah -some:`"Funky Argument`"
If this is code that you can't modify, then things will be complicated.
I also agree with your (unfortunate) conclusion that you will need to create your own custom host to handle this.
You can create additional runspaces easily enough via scripting, but this method isn't accessible in your currently running host (the default console).