Quantcast
Channel: Windows PowerShell - SAPIEN Blog
Viewing all 308 articles
Browse latest View live

PowerShell Studio: Working with Remote Systems (Part 2)

$
0
0

This is the second post in a blog series about working with remote systems using PowerShell Studio.

The following topics are covered:
Part 1 – Caching PowerShell modules from remote systems
Part 2 – PowerShell remoting

In the previous blog post I covered how to use the Cache Export tool to cache module information from a remote system using the Import Remote Cache button, which makes the modules available in the PowerShell Studio Object Browser.

  

 

Part 2 – PowerShell remoting

In this blog post I will show you how to use Windows PowerShell Remoting for remote scripting using PowerShell Studio.

The following topics will be covered:

  • Prerequisite for PowerShell Remoting
  • Adding Functionality using PowerShell Profile
  • PSSession Configuration setup
  • PSSession Configuration name
  • PowerShell Studio “Remote Console”
  • Creating a PSSession Console Host

 

Prerequisite for PowerShell Remoting

Before we start we need to configure our system to support Windows PowerShell Remote with PowerShell Studio.

First, verify that PowerShell is enabled for Remoting by executing the following one-liner:

Enable-PSRemoting -Force

Note: This command enables the computer to receive remote commands via the WS-Management service.

Next, verify that the WS_Management service is running (see image below).  By default, this service will remain in Stopped status with the Startup Type set to Manual.

For more information on how to setup PowerShell Remoting, see these PowerShell Help topics:

  • about_Remote
  • about_Remote_Troubleshooting
## - Display PowerShell Help Topics:
Get-Help about_Remote -Detailed
Get-Help about_Remote_Troubleshooting

Note: Remember that PowerShell help information is available in your system. Execute the “Update-Help -force” command to download PowerShell help topics and cmdlets documentation.

 

Adding Functionality using PowerShell Profile

Although it is not mandatory to create a PowerShell Profile, it is beneficial when adding your own set of custom functions and also when adding PSSnapin’s because they are made available when the PowerShell console is active.

Keep in mind, PowerShell Snap-ins are not modules and are not loaded automatically.  If you are considering using a PowerShell Profile, it will be useful to add PowerShell Snap-ins during the PowerShell Remoting sessions in either Windows PowerShell and PowerShell Studio console.

For more information about how to create a Windows PowerShell Profile and .NET Snap-ins, see these PowerShell Help topics:

  • about_Profiles
  • about_PsSnapins
## - Display PowerShell Help Topics:
Get-Help about_Profiles -Detailed
Get-Help about_PsSnapins

 

PSSession Configuration setup

These steps will need to take place on the remote system that will be accessed from Windows PowerShell, or from PowerShell Studio Consoles.

  1. Create a simple PowerShell Profile
  2. PSSession Startup Script

 

Create a simple PowerShell Profile

The following steps will create a new Windows PowerShell Profile used for All Users and All Hosts. Just make sure to open the Windows PowerShell Console using Run as Administrator:

'function myProfile{ "My System $Env:COMPUTERNAME profile has been loaded!`r`n"+"$($PSVersionTable.PSVersion)"}; MyProfile;' | Out-File $PsHome\Profile.ps1;

 

PSSession Startup Script

Now, in order for the Windows PowerShell Remote session to automatically load the profile, we need to use the Register-PSSessionConfiguration cmdlet with the ‘-StartupScript‘  parameter to include the location of the profile that we just created:

Register-PSSessionConfiguration -Name MyPSSessionProfile -StartupScript $PsHome\Profile.ps1

For more information about how to create a PSSession configuration, see these PowerShell Help topics:

  • Register-PSSessionConfiguration
## - Display PowerShell Help Topics: 
Get-Help Register-PSSessionConfiguration

 

PSSession Configuration name

Finally, using either the Windows PowerShell Console or the PowerShell Studio PowerShell Console, we proceed to create a PowerShell Remote session from our local machine to the remote system. Using the Enter-PSSession cmdlet with the parameter ‘-ConfigurationName’ followed by the name we registered in the PSSession configuraiton command.  This will load the PowerShell Profile during the remote session.

Use the the following one-liner with the correct system name and credentials in either of the Windows PowerShell or the PowerShell Studio console:

Enter-PSSession -ComputerName W2k16SHP01 -Credential trinity\maxt -ConfigurationName MyPSSessionProfile

   

This will verify that we have a successful remote connection to another system via PowerShell Remoting.

 

PowerShell Studio “Remote Console”

If you don’t need to use the PowerShell Profile, PowerShell Studio gives you the ability to do remote scripting thru the Remote Console button found under the Platform ribbon menu.

  

The Remote Console is good for basic system-to-system remoting without the need to create a PSSession configuration name.

 

Creating a PSSession Console Host

If you’re constantly managing multiple systems, it would tedious to perform these steps every time:

  1. Open a script.
  2. Type, or highlight the Enter-PSSession one-liner.
  3. Then, run in console to connect to the remote system.
  4. Repeat the steps for another system.

PowerShell Studio allows for creating additional Console hosts, and we can create remote connections to individual systems. This can be done using the Options button in the Windows ribbon menu. You can add custom consoles in the Console section.

The following sample will be used to create a new console host to remote connect to another system. This will require the name for the Console host, and the command line to execute:

Name: PSSessionToRemoteSystem1

Command line: C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -noexit -Command “Enter-PSSession -ComputerName SystemName -Credential Domain\UserName -ConfigurationName MyPSSessionName”;

Note: Please notice that the one-liner has the system name and credentials hard coded. Also, the parameter ‘-ConfigurationName’ is optional.

When you have added the new console host command line, exit the Option panel and restart PowerShell Studio.

The next time you click on the Console panel, the newly added PSSession Console is available in the console drop-down list:

Select the newly added console “MyPSSessionXXX”, and this will remote connect to the other system.

 

Conclusion

You need to properly configure and test your Windows PowerShell environment to support PSRemoting before you start working with PowerShell Studio against remote systems. Taking advantage of the PowerShell Help documentation and PowerShell Studio features will assist in extending both your local and remote scripting to work interactively with PowerShell on any system.

Note: The overall concept explained in this blog post can be applied to our PrimalScript editor.

 

Related Articles

1. Developing PowerShell scripts for other machines (Part 2).
2. But it works on my machine…

 

Feedback

As always, if you have any ideas, comments, or feedback, please visit our feedback forum and reference this post.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com


SAPIEN Technologies – Europe and Asia Tour 2018

$
0
0

This October I will be traveling to Europe and Asia. During this trip I will be speaking about PowerShell, demonstrating SAPIEN Technologies products, and most importantly I will show how PowerShell Studio can make you a better scripter.

 

Itinerary

October 10th, 2018 (Wednesday)

London – PowerShell Day UK

Full day event

10 South Place (Wilson Street), London, Greater London, E C2M, United Kingdom

Look for us in the sponsor area.

Register at: PSday.UK

 

October 11th, 2018 (Thursday)

Amsterdam

Meeting late afternoon or early evening

Rubrik Offices

Europlaza Building, Hoogoorddreef 54 (5th Floor), 1101 BE Amsterdam, Netherlands

Topic: Intro to using PowerShell for Building Cloud VM’s in Azure

Register at: To be announced

 

October 15th, 2018 (Monday)

Oslo

Meeting in the evening at 6:00 pm

Intility Offices

Schweigaards gate 39, Oslo, Norway

Topic: Intro to using PowerShell for Building Cloud VM’s in Azure

Register at:  Azure-User-Group-Norway

 

October 18-20, 2018 (Thursday – Saturday)

Singapore

All day conference

Microsoft Building

1 Marina Blvd, #22-01 One Marina Boulevard, Singapore

4 hour Workshop on Creating GUI Application with PowerShell Studio and a 1 hour speaking session about PowerShell Core – working with SQL Server Management Objects (SMO) Cross-platform.

Register at: PowerShell Conference Asia 2018

 

If you live in the area, feel free to stop by, check out our products, and see PowerShell in action.

Follow us on Twitter (@maxtrinidad/@SAPIENTech), Linkedin (Maximo Trinidad), and/or Facebook(maximo.trinidad/SAPIENTech)

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

New Video – PowerShell Studio: Working with Tab Control GUI Template

$
0
0

This video demonstrates how to work with the Tab Control GUI template using PowerShell Studio.

In this video you will learn how to:

  • Find the Tab Control template.
  • Add controls to the form.
  • Change control properties in the form.
  • Use Snippets code to add the code behind the form controls.

View the video here: SAPIEN PowerShell Studio Working with Tab Control GUI Template

Additional Tips

Displaying output string to the Rich TextBox Control

The first time using the Rich TextBox control to display the results you will notice that the columns are misaligned. In order to display properly aligned columns, you need to go back to the Rich Textbox property in the Properties panel, select the Font property, and change it from Microsoft Sans Serif to Lucida Console.

 

After you change the Font property, the string output to the Rich TextBox will look properly aligned:

In the Tab Control “Processes”, in the “Filter Process” textbox, use a process name shortname with the “*” asterisk wildcard.

Create Snippet Code

As mentioned in the video, creating snippets is the best way to reuse existing code and also to create a library of reusable code for building new solutions.

Listed below is the code for the three snippets used in the sample Tab Control form:

ButtonGetFolder_Snippet
## - Open Windows GUI to select only Folders using .NET object:
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog;
$FolderBrowser.RootFolder = "Desktop";

$Results = $FolderBrowser.ShowDialog();

if ($Results -eq "OK")
{
$location = $FolderBrowser.SelectedPath.ToString();
$textbox1.Text = $location;
}
ButtonOK_Snippet
## - Code use for Tab Control form ButtonOK
$Err01 = $null; $richtextbox1.Text = $null;
$GetDirectories = Get-ChildItem -Directory $textbox1.Text -ErrorVariable Err01 -ErrorAction SilentlyContinue

If ($Err01.Count -eq 0)
{
$richtextbox1.Text = $GetDirectories | Out-String -Width 1000;
}
else
{
## - Display error notification:
[void][System.Windows.Forms.MessageBox]::Show('Enter a valid folder Name!'+"`r`nError Message:`r`n$Err01", 'Invalid Folder Name');
$textbox1.Text = "Select or Enter folder name...";
};
ButtonOK2_Snippet
## - Code use for Tab Control form Button3 OK
If ($textbox2.Text -eq '')
{
$GetProcesses = Get-process;
$richtextbox2.Text = $GetProcesses | Out-String -Width 1000;
}
else
{
$GetProcesses = Get-process $textbox2.Text;
$richtextbox2.Text = $GetProcesses | Out-String -Width 1000;
};

Feel free to download the SampleTabControlTemplate_11162018.

Related Articles

Feedback

As always, if you have any ideas, comments, or feedback, please visit our feedback forum and reference this post.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

Adding custom menu items to PowerShell tray applications

$
0
0

A while ago we introduced a new packager engine which enables you to create System Tray applications with PowerShell. We have now extended that a little bit and added the ability to create custom menu entries in the tray application’s context menu.

image

I will take the same code we used for the last blog article and show you how to add the custom menu topic and the corresponding handler. The download link for the code is at the end of this article.

To enable you to do anything with the underlying engine which runs your script, we had to add an object which is available as $SAPIENHost. Since this particular object only exists in packaged engines, you need to make sure to check for its existence before using it.

So all custom menu code should be enclosed in if($SAPIENHost -ne $null) { …. }

image

Let’s look at the code. There are three parts:

  1. There is code to see if the registry has an entry pointing to our application to run on startup. If the items don’t match, we make sure to remove the entry—just in case you moved the application.
  2. The second part is the interaction with $SAPIENHost. As you can see, there are only two calls here:
    • First, $SAPIENHost.GetContextMenuStrip() retrieves the .NET object for the tray application’s context menu.
      The underlying .NET type is ContextMenuStrip if you want to look that up. The method GetContextMenuStrip exists in all hosts that have a $SAPIENHost object. It will just return $null if there is no context menu.
    • Second, there is a call to $SAPIENHost.SetMenuHandler. This connects a menu entry to a script block which gets called when a menu item is selected. More on that later.
  3. Last but not least, there is code to construct two objects, a ToolStripSeparator and a ToolStripMenuItem, which we add to the menu. We set the check mark on the menu item if the registry entry is there, otherwise, we make sure it’s off.

This is all normal .NET menu stuff, so nothing exciting.

The SetMenuHandler call has two parameters: The actual menu item object (ToolStripMenuItem), and the name of a script block which will handle that menu item—in our case $Handle_OnStartup.

image

This script block is called each time a user selects the menu item on the tray application’s context menu.

There are a few things to consider:

As you may remember, the main code of our tray application is a loop which sleeps between iterations. Your menu handler is called from a separate thread, which can be problematic. In our example, the menu handler does not interact with anything in the main loop so there is no problem.

If you want to interact with objects in your main script loop, make sure to consider or change the current state of your main operation before accessing and modifying any objects.

Download

You can download the script and the packaged executables here.

You will need PrimalScript 2019 7.4.122 or later to use this. PowerShell Studio 2019 should include the new engines with version 5.6.158 or after. Make sure to check the version log when in doubt.

Feedback

As always, if you have any ideas, comments, or feedback, please use our feedback forum and reference this post.

 

Creating a Windows Application with PowerShell

$
0
0

Not all Windows applications are purely based on Windows Forms. Take Notepad for example; it uses a “form” if you search for a string, but otherwise it’s just a window with a menu and a text box.

PrimalScript and PowerShell Studio’s packager has had a Windows host like that for a while now.
It basically directs all output from the packaged script into a RichText edit control (see this article). This works really well for a small script with a single type of output, but what if we want to enable the end-user to run different tasks at different times? Take this script for example:

image

You can probably tell that in most cases this script will output a large amount of text. It would likely be too much to ask the end-user to sift through the resulting output to find what is needed, so we need to provide a little more structure to select individual queries.

Just as we have done with system tray applications (see this article), we have added access to the menus of our Windows application host.

To get started, we add some code to add a “WMI Queries” entry to the top level menu:

image

As you may recall, in the System Tray application we had a GetContextMenuStrip call on the SAPIENHost object. This time we use the GetMenuStrip call. Why the distinction? Both calls return a menu, but they return different underlying object types. In this case we get the System.Windows.Forms.MenuStrip object. We wanted to keep things clean and not return a different object with the same call, but, most importantly, accessing the main window’s menu strip does not exclude also accessing the context menu of the current window. So we will make use of the GetContextMenuStrip call at a later time.

At any rate, we create a ToolStripMenuItem and add it to the applications main menu. This is done by inserting it into the parent’s Items collection. We want the new item to show up after the “Edit” entry, so we use the index 2 (File = 0, Edit = 1).
image

When we build and run this, we get the desired menu entry.

The next step is to create menu items for each of our functions:
image

We use two properties of the newly created menu items; Name and Text. Name is what we use internally to identify the item, and Text is what the user will see.

We are almost done with setting up the menus. Next we add these items to the drop down menu we inserted:

image

The method to add an item to a collection returns the index of the new item, so we assign that to a variable which prevents unwanted output.

Of course we need to associate these menu items with something to actually handle the menu event:

image

So we create a script block for each menu entry, which looks like this:

image

Each command handler sets a global variable to indicate which command needs to be executed next. It also uses the GetTextView() command to retrieve the RichTextBox object from the host to reset the content.

This is where it gets really interesting, but first let’s build and run to see what we have:

image

We now have the menus in place and the handlers for the menu topics, but that doesn’t really do anything yet. We need to dive a little deeper, but it is not complicated—just a little different than your normal, straightforward linear script.

Just as with a service or a tray application, if we want our script to handle menu events it cannot simply exit after setting everything up. We need a loop at the end of our script, just like we did for the tray app or a packaged Windows Service.

image

We use a loop and switch to handle the command set by the handler via the $global:NextCommand variable. Please understand that the ‘global’ part is essential, because the scope of your script and the scope of the event handler are different.

Why don’t we just execute the command directly in the handler? Because two things are at play here:

  • For one, the outer Windows application and your PowerShell script each run in an individual thread. As the event handlers are called from the application thread, which handles the user interface, there are limits on what you can do directly.
  • Secondly, most PowerShell commands use a pipeline. That pipeline is usually flushed at the end of a command. Since our script is not supposed to end before the application exists, that would never happen so we need to use “| Out-Host”.

PowerShell also strongly objects to executing a CIM command from another thread, so we really need to make sure we call it from the main thread.

You can of course put the actual code in their own functions or script blocks. You do not have to cram all code into the switch statement; we did that simply for illustration purposes.

The code for this sample is available for download.

Feedback

As always, if you have any ideas, comments, or feedback, please use our feedback forum and reference this post.

 

SAPIEN Technologies at the South Florida Code Camp 2019

$
0
0

SAPIEN Technologies is a proud sponsor of the South Florida Code Camp 2019 event organized by the Florida .NET User Groups: Dave Noderer, Scott Katarincic, Rachel Terman, and many others.

From left-to-right: The legendary Russ Fustino, Me (Max Trinidad), and Dave Noderer.

On Friday, March 1, we sponsored the speaker party. It was nice to see everyone and welcome all of the speakers having a good time at “Ye Olde Falcon Pub“:

     

  

Left-to-right: Me (Max Trinidad), Russ Fustino, Alex Funkhouser, and Pierre Donyegro.

On the day of the event, Saturday, March 2, we talked with attendees about SAPIEN Technologies’ products:

  

The event hosted 1315 attendees with 75 speakers covering a broad range of technologies:

   

Congratulations to Byron Bank (right) who won a one-year license subscription to PowerShell Studio 2019:

You can connect with the FlaDotNet User Groups via their MeetUp group and website.

Event and User Group Sponsorship

SAPIEN Technologies is proud to support the PowerShell Community. Feel free to reach out and contact us for both events and user group sponsorship information by sending an email to usergroups@sapien.com.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

 

SAPIEN Technologies at the South Florida SQL Server User Group MeetUp

$
0
0

I enjoyed attending the South Florida SQL Server User Group meeting and showcasing SAPIEN Technologie’s PowerShell Studio 2019 IDE during my “PowerShell Core – Introduction to SQL Server Linux Containers” presentation.

A big “thank you” to the meeting attendees,  and to the user group leaders Cecilia Brusatori and Lowell Izaguirre for inviting me to present.

You can connect with the South Florida SQL Server User Group (SFSSUG) via their MeetUp group or website.

  

We strive to continually enhance the productivity of system administrators and DevOps developers by adding new features to our products. Check out our product line on the SAPIEN Technologie’s site and feel free to contact me (maxt@sapien.com) or SAPIEN Sales (sales@sapien.com) with any questions.

 

Event and User Group Sponsorship

SAPIEN Technologies is proud to support the PowerShell Community. Feel free to reach out and contact us for both events and user group sponsorship information by sending an email to usergroups@sapien.com.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

Progress Bar Series (Part 1) – Displaying Script Progress in GUI Applications

$
0
0

This is the first in a series of articles covering the topic of Progress Bars.

Sometimes a script can take time to complete a task and we need a way to display this in our GUI application. We can add a visual aid to help us see the progress of our script.

There are a number of ways to accomplish this:

  • Write the results to a text file.
  • Write the results to a database table.
  • Display the results in a text or label box in our GUI form.

You can also use the available progress control objects and script commands in your solution:

  • Progress Bar Control
  • Progress Bar Overlay Control
  • ToolStrip Control
  • StatusStrip Control
  • Write-Progress (non-graphical progress bar for console scripting)

All of these controls enable the GUI application to display the progress of the script during execution.

Once you learn to use one, it is easy to use the others since they have most of the same .NET properties and methods for handling the progress bar animation.

To learn more about these properties and methods, check out the following article on the ProgressBar Control.

Progress Bar Display Options

The following images show some options for using the progress bar controls. These can be the starting point for building either simple or complex forms. The complexity is up to you—be creative!

Using the “Progress Bar” control in it’s simplest form, and in a multi-task progress:

     

Using the “Progress Bar Overlay” control gives a better notion of completion by adding text to the progress bar:

       

All of the above GUI forms were created manually. The GUI templates provided with PowerShell Studio can save development time and can also provide ready-to-use code that can be easily modified.

The images below provide examples of the progress bar control added to a pre-existing template.

When you use either the “StatusStrip” or “ToolStrip” control, the progress bar will be added to a specific location on the form. When the “StatusStrip” control is used, the Progress Bar is placed at the bottom of the form:

When the “ToolStrip” control is used, the Progress Bar is placed at the top of the form:

Using either the “Progress Bar” or “Progress bar Overlay” control gives you the ability to add the control anywhere on the form:

If you want to provide a non-graphical progress bar for a console script solution, use the “Write-Progress” cmdlet.  For more information and an example, run the following command:

Get-Help Write-Progress -detailed

Keep in mind that using the “Write-Progress” cmdlet is host dependent—when packaging the application, it won’t work when using either “Silent Engine” or “Windows Form” in a GUI application.

By using any of these controls (or cmdlet) and a few lines of code, we can add the visual aid to help us see what’s going on with our script progress.

Notice that when executing the progress bar in a GUI application, it will become unresponsive until it completes processing the code behind the control. If there is a requirement to give a user the ability to interrupt or cancel the progress operation, you need to build a responsive form.

Check out these articles for information on making a responsive GUI:

I will provide an example of a “Responsive Form” in Part 5 of this series—”Handling Steps Progress with a Background Job in a GUI Application”.

What’s next?

In the upcoming series we will explore some progress bar scenarios, including notion of completion, status notification, and steps progress. Up next is Part 2 where we will cover the progress bar use for notion of completion.

Upcoming series topics:

  • Progress Bar Series (Part 2) – Handling Progress with Notion of Completion in a GUI Application
  • Progress Bar Series (Part 3) – Handling Progress Status Information in a GUI Application
  • Progress Bar Series (Part 4) – Handling Steps Progress with a Background Job in a GUI Application
  • Progress Bar Series (Part 5) – Display Progress in a Script (non-GUI) solution

Related Articles

Feedback

As always, if you have any ideas, comments, or feedback, please visit our feedback forum and reference this post.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com


Progress Bar Series (Part 2) – Handling Progress with Notion of Completion in a GUI Application

$
0
0

This article is Part 2 in our Progress Bar series. In this article, we cover handling a script’s task progress with the notion of completion by using a “Progress Bar” control in a GUI application to provide a visual presentation of what is processing.

Backup Files GUI Scenario

In this scenario, we will develop a GUI application that creates a backup folder that will copy a series of files from a selected folder. This application will include a progress bar to visually show the progress while copying the files.

This application will prompt the user to select the location of the folder containing all text files to be backed up, and it will automatically create the backup folder in the selected folder. “Progress Bar” and “RichTextBox” controls have been added to the form to show what is going on during the process.

The combination of using both controls gives us the notion of completion in our GUI application.

“Select Folder” Button Control

To make the progress bar work, we added the necessary code behind the “Select folder” button control event.  The GUI application will prompt to select the folder containing the files to backup before starting the backup step. These files will be copied to a predefined backup folder-name in the chosen folder location.

After selecting the folder, we save the total number of files.

:
#Get all the text files in the folder
$files = Get-ChildItem $selectedPath -Filter *.txt;
:

Next, we use the saved total files to initialize the progress bar Maximum property. Then we initialize all other properties before starting to display the progress activity.

#Initialize the Progress Bar
$progressbar1.Maximum = $files.Count;
$progressbar1.Step = 1;
$progressbar1.Value = 0;

The progress bar will start with Value property = 0, and use the Step property to increment that Value by 1 when executing the for-each loop. The progress bar will start to increment.

#Copy the files and update the progress bar
$cnt = 1;
foreach ($file in $files)
{
Copy-Item ('{0}\\{1}' -f $selectedPath, $file) -Destination $destination;
$copiedfiles = "$cnt - $($file.name) - copied from $($selectedPath) to $($destination).";
$richtextbox1.AppendText(($copiedfiles | Out-String -Width 1000));
$cnt++;

## - Progress bar method to increment the slider:
$progressbar1.PerformStep();

};

Inside the foreach(..) loop logic, every time the PerformStep() method executes after the copy step the progress bar will increment by 1, as defined in the Step property.

While the GUI application is executing, we can see the progress bar increment as the files are copied to the selected backup folder. At the same time, we can see the information being updated in the RichTextBox area:

  

All of this done is done with just a few lines of code.

Summary

To make the progress bar work, we need to initialize the Maximum value to the total amount of the files being copied. Then we use the PerformStep() method to increment the progress bar.

Below is a general view of the logic used in the progress bar sample:

Download Progress Bar sample form: ProgressBarSimpleTask02.zip

What’s next?

Next up is Part 3 where we will demonstrate the use of the “Progress Bar Overlay” control.

Progress Bar series topics:

  • Progress Bar Series (Part 1) – Displaying Script Progress in GUI Applications
  • Progress Bar Series (Part 2) – Handling Progress with Notion of Completion in a GUI Application
  • Progress Bar Series (Part 3) – Handling Progress Status Information in a GUI Application
  • Progress Bar Series (Part 4) – Handling Steps Progress with a Background Job in a GUI Application
  • Progress Bar Series (Part 5) – Display Progress in a Script (non-GUI) solution

Related Articles

Feedback

As always, if you have any ideas, comments, or feedback, please visit our feedback forum and reference this post.

 

 

SAPIEN Technologies at the Orlando .NET User Group Open Mic Night

$
0
0

On Thursday, March 14, I had the pleasure of participating in the Orlando .NET User Group (ONETUG) Open Mic Night on the eve of their upcoming Orlando Code Camp 2019 event.

This is a dedicated user group with about 15 professionals seeking interesting topics and staying current with the latest technology.

The Open Mic Night had the following three topics:

PowerShell Core – Introduction to SQL Server” – by Maximo Trinidad, SAPIEN Technologies Evangelist.

Kubernetes for .NET developers” – by Facundo Gauna, Software Engineer at Nebbia Technology.

Angular Authentication with Azure AD” – by Phil Hagerman, Full Stack Developer and Front End Enthusiast.

The open mic was fast-paced, with 20-minute time slots allotted for each presenter. The blend of topics provided an opportunity to see how these technologies interact with each other. I enjoyed showing SAPIEN Technologies’ PowerShell Studio 2019 editor working with PowerShell Core from within WSL (Windows Subsystem for Linux) and Docker Containers.

The Orlando .NET User Group meets in the Melrose Tech Center, on the 2nd floor of the Orlando Public Library. You can connect with ONETUG via their MeetUp group.

SAPIEN Technologies strives to enhance the productivity of system administrators and DevOps developers by continually adding new features to our products. Check out our software options and feel free to contact me (maxt@sapien.com) or SAPIEN Sales (sales@sapien.com) with any questions.

 

Event and User Group Sponsorship

SAPIEN Technologies is proud to support the PowerShell Community. Feel free to reach out and contact us for event and user group sponsorship by sending an email to usergroups@sapien.com.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

Progress Bar Series (Part 3) – Handling Progress Status Information in a GUI Application

$
0
0

In Part 3 of the Progress Bar series, we are going to take a more in-depth look at the “Progress Bar Overlay” control. This control allows us to display text in the progress bar while processing the script in the application.

Getting Computer Information Scenario

In this GUI application, we will retrieve some system information and at the same time display each data collection step of the process by using the “Progress Bar Overlay” control.

As the script steps execute, the TextBox control will show the computer name for the data that is being collected. Next, the progress bar will increment as the different script steps complete, and then the RichTextBox control will display the results.

“Get Info” Button Control

The “Progress Bar Overlay” control contains the TextOverlay property, where you can add a text string that will display as the progress bar increments during script execution.

The script’s processing takes place in the code behind the “Get Info” button control. The text box will display the system from which the data is being collected. The computer names are stored in a string array, and then the for-each loop will pick one computer name at a time.

In this scenario, to get the progress bar Maximum property value, we get the total count of items in the array and then multiply by the number of steps. The Step property is set to 1 which will allow the Perform() method to increment the bar by 1.  Using the Start-Sleep cmdlet helps to provide a delay of 1 second to display the “Processing…” text in the progress TextOverlay property, which allows us to see the progress bar increment while executing the script steps in the for-each loop logic.

:
## - Set list of systems:
$svrList = @("$($env:COMPUTERNAME)", "$($env:COMPUTERNAME)");

## - TextOverlay before executing function:(Array count * number of steps)
$progressbaroverlay1.Maximum = $svrList.Count * 3;
$progressbaroverlay1.Step = 1;
$progressbaroverlay1.Value = 0;
$progressbaroverlay1.TextOverlay = "Processing...";
Start-Sleep -Seconds 1;
:

Then, inside the for-each loop in each of the script step’s sections, the following progress bar actions are performed:

  1. The progress bar TextOverlay property displays the step text.
  2. The script step executes.
  3. The progress bar PerformStep() method visually increments the bar.
  4. The Start-Sleep cmdlet at the end of each step gives a slight delay allowing the progress bar to display the script step text.
:
## - Foreach to get system information:
$global:SvrObj += foreach ($name in $svrList)
{
## - Get Computername:
$textbox1.Text = "Collecting information from Computer - $name";

## - Script Step 1:
$progressbaroverlay1.TextOverlay = "Step 1: Get Server Operating System Info...";
$x = get-wmiObject -Class Win32_OperatingSystem -Computername $name `
-ErrorAction 'SilentlyContinue' -ErrorVariable MyError;

$progressbaroverlay1.PerformStep();
Start-Sleep -Seconds 1;

## - Script Step 2:
$progressbaroverlay1.TextOverlay = "Step 2: Get Server Computer System Info...";

$x1 = get-wmiObject -Class Win32_ComputerSystem -Computername $name `
-ErrorAction 'SilentlyContinue' -ErrorVariable MyError;

$progressbaroverlay1.PerformStep();
Start-Sleep -Seconds 1;
## - Script Step 3:
$progressbaroverlay1.TextOverlay = "Step 3: Create $name PSObject ...";

## - Build PSCustomObject:
[PSCustomObject]$SystemInfo = New-Object PSObject -Property @{
ComputerName = $x.csname;
OperatingSystem = $x.Name.Split('|')[0];
LastBootUpTime = $x.ConvertToDateTime($x.LastBootUpTime);
Status = "Success";
Manufacturer = $x1.manufacturer;
SystemModel = $x1.model;
'PhysicalMemory(GB)' = [float]($x1.TotalPhysicalMemory/1gb);
} -ErrorVariable MyError; $SystemInfo

$progressbaroverlay1.PerformStep();
Start-Sleep -Seconds 1;
};
:

  

Now we can see the progress bar increment and display the text for the script step that has executed.

Another variation for this scenario is to use multiple progress bars while executing a series of script steps. This involves modifying the form to display overall progress and also individual step progress while collecting information from each system.

  

As you can see, there are different ways that your application can display progress.

Summary

The scenario outlined above follows the same coding approach as the previous post in the series, except here we are executing a series of script steps. Additionally, using the progress bar overlay allows us to provides details about what is happening by displaying text as the progress bar increments.

Here is a general view of the logic used in the progress bar overlay sample:

Download Progress Bar Overlay sample form: ProgressOverlayMultiTask01.zip

Here is the multi-steps progress bar code overview:

Download the multi-steps progress bar sample form: ProgressOverlayMultiTask02.zip

What’s next?

Next in the series is “Part 4 – Handling Steps Progress with a Background Job in a GUI Application” where we will use a “Progress Bar” control in a “responsive” GUI application with the ability to stop a process.

Progress Bar series topics:

  • Progress Bar Series (Part 1) – Displaying Script Progress in GUI Applications
  • Progress Bar Series (Part 2) – Handling Progress with Notion of Completion in a GUI Application
  • Progress Bar Series (Part 3) – Handling Progress Status Information in a GUI Application
  • Progress Bar Series (Part 4) – Handling Steps Progress with a Background Job in a GUI Application
  • Progress Bar Series (Part 5) – Display Progress in a Script (non-GUI) solution

Related Articles

Feedback

As always, if you have any ideas, comments, or feedback, please visit our feedback forum and reference this post.

SAPIEN Technologies at the Microsoft MVP Summit 2019

$
0
0

Every year Microsoft organizes the MVP Summit event in Redmond, WA. MVPs from around the world are invited to interact with Microsoft product teams during a full week of technical sessions.

This annual event provides the opportunity to collaborate with other MVPs on new and upcoming changes with Microsoft technologies.

 

This year the weather in Redmond was beautiful; warm and sunny with clear blue skies.

  

It was great to see many of my PowerShell, SQL Server, and other MVP friends. It was also nice to see Jeffrey Snover and the PowerShell Team—including Joey Aiello, Tyler Leonard, Steve Lee, and many others—as well as others no longer with Microsoft such as James Brundage and Bruce Payette.

Dinner with PowerShell MVPs: Bruce and James.

I was pleased with all of the session content and had the opportunity to learn new things.

MVPs pulling together for a special session “AutoRest PowerShell Cmdlet Generator” by Garret Serack (not NDA)

PowerShell is clearly not slowing down as evidenced by the strength of its use in many Microsoft products, and also by its crossover to many Linux distributions and MacOS.

If you have the need for PowerShell training please contact me (maxt@sapien.com) or SAPIEN Sales (sales@sapien.com) for information on our upcoming training schedule. Also be sure to check out our software options.

Event and User Group Sponsorship

SAPIEN Technologies is proud to support the PowerShell Community. Feel free to reach out and contact us for event and user group sponsorship by sending an email to usergroups@sapien.com.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

 

Progress Bar Series (Part 4) – Handling Steps Progress with a Background Job in a GUI Application

$
0
0

In Part 4 of the Progress Bar series, we integrate a progress bar control in a GUI application that submits a job for background processing. We also demonstrate how to interrupt the running job.

GUI Application for Listing PDF Documents

In this scenario, we show the use of the progress bar while processing a background job. This application is an example of a “responsive” form which prevents the form from freezing during job execution. The form also provides an option to interrupt the job at any time and includes a time-lapse display.

“Start Job” Button Control

In the “Start Job” button control script block, we add the code to initialize the progress bar properties after a folder is selected.

After selecting a folder containing PDF files, we get the total number of files and use that in the Progress Bar Maximum property. Then we initialized both Step and Value properties to 1.

#Initialize the Progress Bar
$progressbar1.Maximum = $files.Count;
$progressbar1.Step = 1;
$progressbar1.Value = 1;

In the “Start Job” button script block, we use our Add-JobTracker Helper function. The following parameters are defined in this function to handle the background job process:

  • Name – The Job-Name for the running job.
  • ArgumentList – (Optional) A single value or an array of values to pass as an Argument to the job.
  • JobScript  – The script code that will be sent to run the background job.
  • UpdateScript – The script code used to update what is going on with the background job.
  • CompletedScript – The script code that will execute when the background job completes processing.

A splatting variable is created holding the parameter’s value to be passed to the Add-JobTracker function:

#Initialize the Progress Bar
$progressbar1.Maximum = $files.Count;
$progressbar1.Step = 1;
$progressbar1.Value = 1;

## - Prepare Splatter variable to submit to background job:
$jobsplat = @{
	Name		    = 'MyJobName'
	ArgumentList    = $selectedPath
	JobScript	    = $jobScript
	UpdateScript    = $updateScript
	CompletedScript = $completedScript
}

At this point, the function will submit the job for processing in the background.

During Job Processing

While the job is processing in the background, the PDF files in the selected folder are being displayed in the output “RichTextBox” control, the timer is counting, and the progress bar increments while processing.

All of this action is being handled by the “UpdateScript” script block section in the Add-JobTracker function:

$updateScript = {
	Param ($Job)
	
	if ($Job.Name -eq 'GetFiles')
	{
		
		## - Grab results from background job:
		$results = Receive-Job -Job $Job
		$richtextbox1.Lines += $results | select -ExpandProperty Fullname
		
		## - Make the text scroll-up while processing:
		$richtextbox1.SelectionStart = $richtextbox1.Text.Length
		$richtextbox1.ScrollToCaret()
		
		## - Increment progress bar:
		$progressbar1.PerformStep();
		
	}
	
	#Animate the Button
	if ($null -ne $buttonStartJob.ImageList)
	{
		if ($buttonStartJob.ImageIndex -lt $buttonStartJob.ImageList.Images.Count - 1)
		{
			$buttonStartJob.ImageIndex += 1
			
			## - Code to Display Time Elapsed:
			$CurrentTime = $Script:Time.Elapsed;
			$DisplayTime = $([string]::Format("Time: {0:d2}:{1:d2}:{2:d2}",
					$CurrentTime.hours,
					$CurrentTime.minutes,
					$CurrentTime.seconds));
			$labelTime.Text = $DisplayTime;
			
		}
		else
		{
			$buttonStartJob.ImageIndex = 0
		}
	}
}

In this section, the progress bar method PerformStep() will trigger the bar to increment.

When the background job ends, the “CompletedScript” script block section executes.  At this point, the total number of PDF files found will display in the “RichTextBox” output area, the total duration of the process will be displayed, and the progress bar will increment to completion.

$completedScript = {
	Param($Job)
	
	if ($Job.Name -eq 'GetPDFFiles')
	{
		## - Get Background Job results:
		$results = Receive-Job -Job $Job;
		$richtextbox1.Lines += $results | select -ExpandProperty Fullname;
		
		## - Display Process Stopped text:
		$richtextbox1.AppendText(("`r`n`r`n*** Process Completed ***`r`n"));
		
		## - Display processing time:
		$richtextbox1.AppendText("`r`n" + "Total Processing $($labelTime.Text)" + "`r`n");
		
		## - Scroll top end of lines:
		$richtextbox1.SelectionStart = $richtextbox1.Text.Length + 4;
		$richtextbox1.ScrollToCaret();
		
		## - Progress Bar fill to end:
		$progressbar1.Increment($richtextbox1.Text.Length);
		$progressbar1.PerformStep();

   }
    
	#Enable the Button
	$buttonStartJob.ImageIndex = -1
	$buttonStartJob.Enabled = $true
	
}

In this section, we use the progress bar method PerformStep() to help complete the bar.

Interrupt the Job

This application includes the ability to stop the job with the “Stop Job” button control. When the job is stopped, the progress bar will stay idle without any increments.

In the “Stop Job” control, both progress bar Value and Step properties are set to 0:

$buttonStopJob_Click = {
	
	Stop-JobTracker
        $this.Enabled = $false
	$buttonStartJob.Enabled = $false
	
	## - Progress bar stop and reset values to 0:
	$progressbar1.Value = 0;
	$progressbar1.Step = 0;
	
	## - Process Abort text:
	$richtextbox1.AppendText(("`r`n`r`n*** Process Stopped ***`r`n"));
}

As you can see, it was simple to integrate the progress bar properties in the Add-Tracker function script block with the button controls.

Summary

We have shown how to integrate the progress bar in a “responsive” application that is handling a background job, with the ability to interrupt the job.

Below is a general view of the logic used in this GUI application sample:

Download Progress Bar sample form: ProgressBarJobTracker_wStopOption1.zip

What’s next?

Next in the series is “Part 5 – Display Progress in a Script (non-GUI) solution”, where will be using the “Write-Progress” cmdlet.

Progress Bar series topics:

Related Articles

Feedback

As always, if you have any ideas, comments, or feedback, please visit our feedback forum and reference this post.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

SAPIEN Technologies at the Orlando Code Camp 2019

$
0
0

SAPIEN Technologies is proud to be a repeat sponsor of the Orlando Code Camp event organized by ONETUG (Orlando .NET User Group).

 

The event had 621 registered attendees, with 90 speakers and 92 sessions.

The speaker dinner party the night before the event was well attended:

I appreciate the opportunity to speak before John Papa’s keynote speech.

  

A large percentage of people attended the event for the first time—during my PowerShell session, most of the attendees were new to PowerShell! It is great to see people interested in learning new technologies.

 

Thanks to the ONETUG organizers for having us as a sponsor: Chelsea Costner, Santosh Hari, Rush Frisby, Esteban Garcia, Brian Mishler, and volunteers.

If anyone wants to join the Orlando .NET User Group (ONETUG), check out their MeetUp group.

Event and User Group Sponsorship

SAPIEN Technologies is proud to support the PowerShell Community. Feel free to reach out and contact us for event and user group sponsorship by sending an email to usergroups@sapien.com.

 

Max Trinidad is a Technology Evangelist at SAPIEN Technologies Inc., and a Microsoft PowerShell MVP. You can reach him at maxt@sapien.com

Why can’t I edit my PowerShell script?

$
0
0
I was sitting in on our recent PowerShell training class, and I observed our amazing trainer, Jason Yoder, field a question from a new PowerShell user asking why she couldn’t edit her script in PowerShell Studio. It turns out that…

Progress Bar Series (Part 5) – Display Progress in a non-GUI Script

$
0
0
In Part 5 of the Progress Bar series we take a look at the Write-Progress cmdlet, which can be used to display task progress in a non-GUI script. This cmdlet is available in Windows PowerShell and PowerShell Core (cross-platform). There…

PowerShell: Property Hijacking!

$
0
0
We interrupt our normally scheduled blog for this Public Service Announcement: Do you use HashTable in your scripts? Have you ever enumerated through the HashTables Keys or checked the HashTable’s Count property? If you have, then you may be the…

Advanced PowerShell Functions: Begin to Process to End

$
0
0
The PowerShell pipeline can pass objects from one command to another, enabling output from a function to stream – or ‘pipe’ – as input into another command. In this article we will demonstrate how to leverage this functionality to seamlessly…

PowerShell Studio: Working with Images in a RichTextBox Control

$
0
0
In this blog post we take a look at how to include images in a RichTextBox Control for a GUI application. This may be helpful if you have a scenario where you want to display a selected image with the…

PowerShell Studio: Pester Integration

$
0
0
The v5.6.164 service build introduces Pester integration into PowerShell Studio. For those who are not familiar with the Pester module, it is a testing framework for PowerShell. The module allows you to run unit tests on your scripts and functions.…
Viewing all 308 articles
Browse latest View live