windows-powershell-docs
windows-powershell-docs copied to clipboard
Write-Progress not work anymore after calling New-WebAppPool from c#
Hello, I have a c# script code invocation that call a powershell script that use the New-WebAppPool command.
The c# code:
var targetScriptFilename = Path.Combine(@"c:\temp\", @"Untitled1.ps1");
using (var powerShellInstance = PowerShell.Create())
{
powerShellInstance.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted");
powerShellInstance.Invoke();
powerShellInstance.AddCommand(targetScriptFilename);
powerShellInstance.Streams.Progress.DataAdded += (obj, eventArgs) => WriteCallback(obj, eventArgs, "progress");
var output = powerShellInstance.BeginInvoke();
while (!output.IsCompleted)
{
Thread.Sleep(500);
}
IEnumerable<PSObject> result = powerShellInstance.EndInvoke(output);
return !powerShellInstance.HadErrors;
}
private void WriteCallback(object o, DataAddedEventArgs args, string type)
{
var records = o as PSDataCollection<ProgressRecord>;
if (records != null)
{
var record = records[args.Index];
var activity = record.Activity;
var description = record.StatusDescription;
var msg = $"{activity}: {description}";
if (string.IsNullOrWhiteSpace(description)) { msg = $"{activity}"; }
else if (activity.EndsWith(".")) { msg = $"{activity} ({description})"; }
Console.WriteLine($"{type}: {msg}");
}
}
The powershell script:
Write-Progress "Script Start"
Write-Progress "Pre add web pool"
New-WebAppPool -Name "Testpool"
Write-Progress "Post add web pool"
Write-Progress "Script End"
The output is:
progress: Script Start: Processing
progress: Pre add web pool: Processing
progress: Preparing modules for first use.
As you can see the trace "Post add web pool" and "Script End" are not present.
There is some errors on my script or some workaround in order to fix the problem?
Thanks