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

Convince My Manager! PowerShell Studio 2015 Killer Features

$
0
0

PowerShell scripters often send us requests for help and post them on our busy forums. None hits home with me like a request for help convincing a cash-strapped IT manager that they should buy professional tools, like PowerShell Studio, for their staff, because I’ve been in the same position. Importantly, this question almost always comes from IT pros, because development managers routinely spend thousands of dollars on professional tools for developers.

IT pros are professionals and they deserve professional development tools. Nonetheless, it’s important to make a clear and convincing case for your manager.

So, here’s a list of the major features of PowerShell Studio 2015. I’ve set the priority order to the things that are most likely to make you extremely efficient, productive, and accurate.

If your favorite feature is missing from this list, post a comment and I’ll add it.

Productivity

· Fully-featured editor with configurable syntax coloring, syntax checking, enclosure matching, advanced navigation, auto-complete for commands, parameters, parameter values, enumerators, WMI classes and properties, .NET Framework classes and members, and help topics. Prompts and enters complete or mandatory elements of parameter sets.

· PowerShell Console in PowerShell Studio runs in an independent process, so you can experiment in the console without jeopardizing the scripts in progress in the editor. Let’s you test commands and scripts in the default console with a persistent session.

· Function Builder and Parameter Builder generate accurate, syntactically correct function and script parameter syntax, including cmdlet attributes, parameter sets, parameter types and attributes, including validation attributes.

· Build PowerShell modules automatically from functions in scripts. PowerShell Studio generates the module manifest for you, complete with GUID and default key settings.

· Automatic formatting insures that scripts are easy to read, debug, and maintain, including indentation, enclosures, and quotation marks. Formatting is fully customizable, including all elements and formatting triggers. The Format Script button reformats an entire script on demand.

· Customizable layouts place all PowerShell Studio tools within easy reach of the scripter, including an Object Browser, Toolbox, Properties page, Function navigator, Help pane, and the source control tool of your choice. Just right-click, submit to source control.

· Create projects and file groups that let you open and manage multiple files from multiple sources in a single operation without changing the source file types or content.

Accuracy

· Execution environment: PowerShell Studio runs each script in a new, clean execution environment free of preferences, profiles, non-core modules, and local variables. To run script commands sequentially in a persistent session with user-specific elements, like profiles, use the built-in PowerShell Console (Run in Console).

· PowerShell Studio debugger has features typically found only in professional development debuggers, including a variables window, watch window, stack trace, and a debug console that is independent of the default (run) console. PowerShell Studio test tools include a history of parameters and values from each script execution instance.

· Advanced remote scripting and debugging: Save remote computers (and credentials) and click once to run any script or to debug a script on a remote computer.

· Snippets: PowerShell Studio comes with an extensive library of reusable code snippets. It lets you save any text or code block as a snippet to automate code development and prevent errors.

Innovation

· Create GUI applications from Windows PowerShell scripts. Excellent for delegating tasks to people who don’t know PowerShell and insuring uniform operations. Drag and drop the Windows Forms UI elements and insert PowerShell commands. PowerShell Studio handles all complex tasks, including loading assemblies, instantiating objects, and registering event handlers. It even inserts helper functions to simplify management of complex controls.

· Create executable files (.exe) from Windows PowerShell scripts. PowerShell Studio wraps any script in an executable file. Including digital signatures and runtime manifests that run the .exe file only on specified computer for specified users in specified environments.

· Create Microsoft Installers (.msi) from multiple files, then deploy or burn to a CD without changing your view.

Best Practices

· Digital signatures: PowerShell Studio signs your scripts, modules, executable files, and MSIs automatically or on-demand.

· Source control integration, including restore points for all scripts, configurable auto-save, and right-click submit file.

· Set execution policy and elevate session toggles help you keep your session more secure without restarting and interrupting your work.

· Generate PowerShell help for your scripts and functions with the correct syntax for comment-based help. For XML help, see PowerShell HelpWriter.

· Convert aliases to full names of cmdlets and parameters with a keystroke.

· Toggle quotation marks from single to double, using double quotes only when needed for variable resolution.

 

In summary:

— Cost of PowerShell Studio: $389
— Cost of not having users contact you every time they need a task performed: Priceless

I hope this helps in your discussions. Again, comment to add your favorite feature and feel free to edit for your environment and the features that you’re most likely to use.

If I was a manager, I’d be convinced!

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell Studio 2015: Service Release with PowerShell V5 Support

$
0
0

We are happy to announce the release of the latest service build of PowerShell Studio 2015 (v4.2.89). You will find that this service build is pack with new features and enhancements. We listened to your feedback and strived to improve your user experience and productivity. We also made improvements to PowerShell Studio’s memory usage and performance.

Note: This build of PowerShell Studio 2015 requires the .NET 4.5 runtime.

PowerShell V5 Support!

The major addition in this service build is official support for Windows PowerShell V5.

image

Classes and Enumerators

PowerShell V5 adds support for classes and enumerators and PowerShell Studio will now display them in the Functions Panel:

Function Explorer and Classes

Snippets

We cleaned up some outdated snippets and added new ones (including PowerShell V5 specific ones).

image

Detect New Versions of Windows PowerShell

PowerShell Studio now detects when new versions of Windows PowerShell are installed. You no longer have to manually run the RegisterControls.exe or rebuild the cache. PowerShell Studio will automatically register the necessary controls and update the cache for you.

 

Deferred File Loading

PowerShell Studio now loads files on demand. Deferred loading improves overall performance when loading large groups of files while reducing memory consumption and load times.

image

You can disable this feature by un-checking Options->General->Enable deferred file loading.

 

Editor Improvements and Additions

We added several new options and features to PowerShell Studio’s editor.

Command Parameter Completion

You will notice a new popup window show up when typing a space after a command:

image

This popup window will display and allow you to cycle through the command’s parameter sets. You can auto-insert the parameters by pressing [TAB] while the parameter set popup is visible.

image

Tip
Press [TAB] to cycle through the parameter fields.

Tip
You can choose to only insert the mandatory parameters by pressing [TAB + Shift].

image

You can enable or disable the parameter set popup in Options->Editor: Show parameter set info after command.

Tip

To display the parameter set information press [CTRL + Shift + Space] while the caret is on or immediately after the command.

 

Auto-complete closing quotes, parenthesis, braces and more

We added new options to auto-complete the following characters while you type:

  • Quotes (single and double)
  • Parentheses
  • Square brackets
  • Curly braces

You can enable or disable these auto-complete features in Options->Editor.

Wrap Commands

We added the following commands which let you quickly wrap the selected text in quotes or braces:

Keyboard Shortcut Wrap Selection In
Ctrl + Shift + 9 ( )
Ctrl + [ [ ]
Ctrl + Shift + [ { }
Ctrl + ‘ ‘ ‘
Ctrl + Shift + ‘ ” “

 

Tip
Use the wrap commands when working with existing code. It makes it easy to place an existing block of code within curly braces { }.

 

Toggle String Quotes

You can now toggle a string’s quotes between single and double by pressing [Ctrl + Alt + ‘].

 

New Parameter Dialog

We overhauled the parameters dialog that appears when running a script with parameters. This new parameter dialog will help simplify passing parameters to a script while running or debugging a script.

image

When you first run a script, the parameter dialog will automatically display the script file’s default parameter set for you.

Tip
Press [TAB] to cycle through the parameter fields.

image

If you wish to change the input parameters you can use combo box on the top to select from the script file’s different parameter sets and previously submitted parameters.

image

Tip
Use the UP and DOWN keys to cycle through the parameter sets and history while typing in the edit box.

File Groups

File groups allow you to open a group of file without creating a project. File groups (.filegroup) are now added to recently used file list when opened. In addition, the order of the files is now preserved when creating a new file group.

 

New Options for existing features

We added the following options to so you can further customize your PowerShell Studio scripting environment:

  • Enable/disable output panel auto-displaying (Options->Panels).
  • Show command aliases in PrimalSense list (Options->Editor).
  • Show parameter aliases in PrimalSense list (Options->Editor).
  • Enable/disable PrimalSense word completion while typing (Options->Editor).

Many of the new features included in the service builds are suggestions from users like you. Therefore if you have any suggestions or feature requests, please share them with us on our Wish List and Feature Requests forum.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell GUIs: Where do I start?

$
0
0

I’ve been using Windows PowerShell since the very first version of Monad in 2005, but PowerShell-based applications with a graphic user interface (GUI) are a whole new world. Instead of thinking of cmdlets and parameters or properties and methods, you need to think in object events. And because there’s no console with .ps1xml-directed views, you need manage all output streams, including standard output and errors.

Most importantly, because you’re dealing with real users, you need to assume that people will type and click whatever they please in whatever order you let them. It reminds me of turning the car over to my teenagers for the first time. In a GUI app, the user drives. So, if you don’t want them to go somewhere, you need to enable and reveal parts of the interface selectively.

PowerShell Studio automates the complex parts, including loading assemblies, instantiating objects, and registering event handlers, so you can focus on making great PowerShell GUI apps.

image

Here are some of the fabulous resources that I used to help me learn how to create PowerShell GUIs. If you have a favorite book, tutorial, or blog post, comment and I’ll add it to this post.

My First PowerShell GUI

If you’re starting from scratch, start here:

 

 

Basic GUI App Techniques

Now that you have the basics, avoid the most common errors encountered by scripters moving to GUI apps:

 

Easy, but Sophisticated

These easy and quick techniques make your GUI apps more usable. They take just minutes to master.

 

Best Practices for UI Design

Where do I put that button? Should I center the textbox? You might be new to GUI app development, but your GUI apps don’t have to advertise it. Learn from user experience and human factors engineers about best practices for UI design.

  • About Face: The Essentials of Interaction Design 4th Edition by Alan Cooper, Robert Reimann, David Cronin, & Christopher Noessel
    Learn the principles of UI design from people who study user-computer interaction. An excellent book for beginners and experienced designers.
  • 9 Things I Learned in UX Grad School by Sara Ford
    Sara summarizes the practical elements of academic UX research for the UI designer, including “Why ‘Developer Speak’ in UI is so bad ” and “Why people make errors”
  • User Interface Design for Administrators
    When do you use a button? When are radio buttons better than checkboxes? SAPIEN Chief Technology Officer, Alexander Riedel, creates a control table that you’ll refer to again and again.
  • Single Form or Multiple Dialogs?
    How much is too much on a single form? Learn the guidelines that professional UI developers use to make this critical decision.

 

 

One-A-Day:  Explore the Windows Forms Controls

One of the best, and easiest, ways to learn the UI controls, is to read our Spotlight articles and try the examples. You can read the MSDN documentation about Windows Forms controls, but our Spotlight articles, designed for PowerShell scripters, focus on the most important features of each UI control, and get you going with PowerShell examples.

Use your “Month of Lunches” habit to explore one new control each day.

In PowerShell Studio, to open a Spotlight article about a control:

  • In the Toolbox or Property pane, right-click a control and then click View Spotlight Article.
  • Or, in the Designer window, right a control, click Help, and then click View Spotlight Article.

image

Spotlight Articles:

Form ImageList StatusBar
Button ListView StatusStrip
Textbox MaskedTextBox TabControl
ComboBox NotifyIcon Timer
CheckBox PictureBox ToolTip
ContextMenuStrip ProgressBar TreeView
ErrorProvider RadioButton

 

 

If you have suggestions that might help other scripters, leave a comment or tweet it to me at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell Studio 2015: Service Release v4.2.90

$
0
0

We released a new service release for PowerShell Studio 2015 (v4.2.90).

Here’s what’s new:

 

Updated Editor Themes

We updated the editor’s themes including the default, so be sure to apply the new PowerShell Studio theme after updating. These themes take into account the new additions to the syntax coloring (see below).

 Editor Presets

For those who don’t like change, we included a PowerShell Studio (Classic) Theme, so that you can revert to the classic look of PowerShell Studio.

Improved Syntax Color

We improved the syntax coloring in PowerShell Studio to give you more control over the coloring of your scripts.

For example:

Unknown parameters are now marked as unknown and colored:

Unknown Parameters

Command arguments can now be colored:

image

Loop labels are now colored as well:

Loop label coloring

 

Improved PrimalSense

We made some enhancements to our PrimalSense.

After debugging, PowerShell Studio will display the last known value for a variable:

image

Note: Array values must be queried before they are stored.

Now PowerShell Studio retains the Variable panel contents for your reference:

Variables panel retains last known values

We improved our PrimalSense support for PSParameterBounds:

PSBoundParameters PrimalSense

We added PrimalSense support for loop labels:

PrimalSense for loop labels

We now display PrimalSense for comma delimited parameter values:

PrimalSense for comma delimited values

Updated Function Browser

The function browser now displays nested functions under the parent function:

Nested Functions

 

Remove Digital Signature

We added the option to remove the digital signature of a script. The recommended practice if you are using the script as part of a project and have the file’s Build property set to Include.

image

We also added the option to sign and remove signatures via the file tab’s context menu:

image

 

Qualify Cmdlet Names

Press [Ctrl + Shift + H] to expand all cmdlets to their module-qualified names:

Unqualified name

Qualified name

Press [Ctrl + Alt + H] to convert all cmdlets to their unqualified name.

 

Please continue providing your feedback. Many of the new features included in the service builds are suggestions from users like you. Therefore if you have any suggestions or feature requests, please share them with us on our Wish List and Feature Requests forum.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

Typing Enter Pushes a Button

$
0
0

As a beginner developer of PowerShell GUIs, I’m always looking for easy ways to make my simple applications more sophisticated and usable. One of the basic usability features in most applications is typing <Enter> in a textbox to invoke a function instead of clicking a Start, Go, or OK button.

In this post, I’ll show you two ways to do it. One technique is significantly simpler than the other, but works only when there is exactly one “Go” button. The more complex technique works for multiple buttons and keys other than <Enter>.

Registering a KeyDown Event Handler

Let’s start with the general, more complex technique. We’ll create a KeyDown event handler for the <Enter> key, but you can use the same method to register an event handler for any key. Our event handler will click a particular button, but you can set it up to click any button on the user’s behalf.

Here’s the typical situation. In this little app, when you type a valid value in the textbox, the Get-Service button is enabled. You can click the Get-Service button, but it would be nice to let the user just type <Enter> after typing the computer name.

GetServicePsf

To enable the “press <Enter>” feature, use the KeyDown event of the Textbox object (System.Windows.Forms.Textbox):

1. Start by creating a variable to hold the KeyDown event of the textbox. Following the best practice naming guidelines, I’ll name the variable $textboxComputerName_KeyDown.

$textboxComputerName_KeyDown = {}

2. The KeyDown event handler requires a KeyEventHandler object, so we’ll cast the script block as a KeyEventHandler object.

$textboxComputerName_KeyDown = [System.Windows.Forms.KeyEventHandler]{}

3. When the KeyCode property value ($_.KeyCode) is “Enter”, we want to click the Get-Service button on the user’s behalf. To click the button, call the Invoke() method of the Click event of the button ($buttonGetService.Click). Referencing the Click event without calling the Invoke() method has no effect.

$textboxComputerName_KeyDown = [System.Windows.Forms.KeyEventHandler]{
    if ($_.KeyCode -eq 'Enter')
    {
        $buttonGetServices_Click.Invoke()
    }
}

4. Set the SuppressKeyPress property of the KeyEventArgs object to $True.

When you invoke the Click event of the button on the user’s behalf, you want to prevent the user from clicking the button, too. Otherwise, the button could be clicked multiple times. Also, the Click generates a sound that’s typically associated with clicking a button, but not with pressing <Enter>. Setting SuppressKeyPress to $True takes care of this for you.

$textboxComputerName_KeyDown = [System.Windows.Forms.KeyEventHandler]{
 
    if ($_.KeyCode -eq 'Enter')
    {
        $buttonGetServices_Click.Invoke()
 
        #Suppress sound from unexpected use of enter on keyPress/keyUp
        $_.SuppressKeyPress = $true
    }
}

The KeyDown event handler is now complete.

The final step is to register the KeyDown event handler, that is, to associate the event hander with the KeyDown event so that when the KeyDown event happens (“is raised”), the system runs the event handler code. Because KeyDown is not the default event of a Textbox object, PowerShell Studio doesn’t do it for you, but it’s very easy to do.

To register the event handler in PowerShell Studio:

1. In PowerShell Studio, in the Designer window, click the textbox.

2. In the Properties pane for the textbox, on the row for the KeyDown event, type the name of the event handler.

clip_image004

To register the event manually (without PowerShell Studio):

1. Write a statement that registers the event handler.

The syntax is:

.add_()

For example:

$textboxComputerName.add_KeyDown($textboxComputerName_KeyDown)

2. Remember to remove the event handler in your cleanup step.

For example:

$textboxComputerName.remove_KeyDown($textboxComputerName_KeyDown)

Set the Accept Button of the Form

Writing a KeyDown event is conceptually a bit complex, but it’s not difficult to do. However, the other technique is so simple that you’ll use it whenever you can.

Every form has an AcceptButton property that is invoked automatically when the user types <Enter>. Typically, the AcceptButton property is set to the OK button, if there is one, but you can set it to any button on the form (or not set it).

NOTE: In PowerShell Studio, when you use a form template that includes an OK button, such as a Dialog Style form, the AcceptButton is set to the OK button by default.

In the PowerShell Studio designer and in the running application, the AcceptButton is indicated by a blue border.

clip_image006

To set the AcceptButton property of the form:
— In the Properties box for the form, in the row for the AcceptButton property, use the drop-down menu to select a button.

clip_image007

-or-

— In the Load event of the form, set the AcceptButton property of the form to the desired button.

$formGetService_Load = {
    $formGetService.AcceptButton = $buttonGetService
}

 

Now that you know both techniques, remember not to use them together. If the AcceptButton property of the form is set to any button, that property value takes precedence over a KeyDown event with an ‘Enter’ key code. For example, if you write a KeyDown event for $buttonGetServices and set the AcceptButton property of the form is $buttonOK, when you click enter in the textbox, it clicks $buttonOK.

Allowing the user to press <Enter> in your app, instead of forcing them to click a button, improves the usability of your app. Spend an extra few minutes setting the AcceptButton property, or even registering a KeyDown event.

June Blender is a technology evangelist at SAPIEN Technologies, Inc and a Windows PowerShell MVP. You can reach her at juneb@sapien.com and follow her on Twitter at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell Studio 2015: Service Release v4.2.92

$
0
0

We released a new service release for PowerShell Studio 2015 (v4.2.92).

Here’s what’s new:


Memory Improvements

In this build we improved PowerShell Studio’s file memory usage. Larger files should now load faster and use up less memory than in previous builds of the product.

 

Rename Controls:

We added a “Rename” command to the GUI designer’s context menu:

Designer context menu

When clicked, the command will take you directly to the name property in the Properties Panel:

Editing Name property

Then you simply begin typing in the new name for the control, without any unnecessary mouse clicks.

 

Refresh Help:

We added a “Refresh Help” command to the PowerShell Panel’s context menu:

PowerShell Panel Refresh Help

This command will update the cache help for the selected module.

Refreshing help message

The generated help is shared between the SAPIEN Document Explorer and PrimalScript 2015.

If help is coming up blank for a particular module, this command can build the necessary cache files so that it will appear when editing your scripts.

Help for custom modules

 

Execute Selection in Debug Console

We renamed the editor context menu command “Run Selection in Debug Console” to “Execute Selection in Debug Console”. The new name reflects the functional differences between the “Run Selection” and “Execute Selection in Debug Console”.

The default behavior for the “Run Selection” commands is to run the current line if there is no selection made. This is no longer the case for “Execute Selection in Debug Console” command. Instead it will behave like the “Add To Watch” command where if you use the “Add To Watch” command on a property or method of a variable, it will automatically include the whole statement.

Execute Debug Console on a member of a variable

In the case where you have a selection, it will instead run the selection.  

 

Please continue providing your feedback. Many of the new features included in the service builds are suggestions from users like you. Therefore if you have any suggestions or feature requests, please share them with us on our Wish List and Feature Requests forum.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

Get Commands in a Nested Module

$
0
0

Many Windows PowerShell modules include nested modules. In fact, some of your favorite cmdlets might be in a nested module, but you wouldn’t typically know it. Nested modules are reusable, so you can repackage and use nested modules independently and in other modules, unless, of course, they require something in the parent module. For example, you can use a nested module in a custom session configuration when the user doesn’t need and shouldn’t have the entire module.

The ModuleInfo and ModuleInfoGrouping objects that the Get-Module cmdlet returns have a NestedModules property. So, to find modules with nested modules, use this command:

Get-Module –ListAvailable | where NestedModules

To find the nested modules in a particular module, use a command with this format:

(Get-Module –ListAvailable $ModuleName).NestedModules

For example, the NetAdapter module has 19 nested modules. (CIM modules typically have lots of nested modules.)

PS C:\> (Get-Module -ListAvailable NetAdapter).NestedModules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Cim        1.0        MSFT_NetAdapter.cmdletDefinition    {Get-NetAdapter, Enable-N
Cim        1.0        MSFT_NetAdapterAdvancedProperty.... {Get-NetAdapterAdvancedPr
Cim        1.0        MSFT_NetAdapterBinding.cmdletDef... {Get-NetAdapterBinding, S
Cim        1.0        MSFT_NetAdapterChecksumOffload      {Get-NetAdapterChecksumOf
Cim        1.0        MSFT_NetAdapterEncapsulatedPacke... {Get-NetAdapterEncapsulat
Cim        1.0        MSFT_NetAdapterHardwareInfo.cmdl... Get-NetAdapterHardwareInf
Cim        1.0        MSFT_NetAdapterIPsecOffload         {Get-NetAdapterIPsecOfflo
Cim        1.0        MSFT_NetAdapterLso                  {Get-NetAdapterLso, Set-N
Cim        1.0        MSFT_NetAdapterPowerManagement.c... {Get-NetAdapterPowerManag
Cim        1.0        MSFT_NetAdapterQos                  {Get-NetAdapterQos, Set-N
Cim        1.0        MSFT_NetAdapterRdma                 {Get-NetAdapterRdma, Set-
Cim        1.0        MSFT_NetAdapterRsc                  {Get-NetAdapterRsc, Set-N
Cim        1.0        MSFT_NetAdapterRss.cmdletDefinition {Get-NetAdapterRss, Set-N
Cim        1.0        MSFT_NetAdapterSriov                {Get-NetAdapterSriov, Set
Cim        1.0        MSFT_NetAdapterSriovVf.cmdletDef... Get-NetAdapterSriovVf
Cim        1.0        MSFT_NetAdapterStatistics.cmdlet... Get-NetAdapterStatistics
Cim        1.0        MSFT_NetAdapterVmq.cmdletDefinition {Get-NetAdapterVmq, Set-N
Cim        1.0        MSFT_NetAdapterVmqQueue.cmdletDe... Get-NetAdapterVmqQueue
Cim        1.0        MSFT_NetAdapterVPort.cmdletDefin... Get-NetAdapterVPort

Sadly, you can’t use Module parameter of Get-Command to get the commands in a nested module.

PS C:\> Get-Command -Module MSFT_NetAdapterQos
PS C:\>

But, it’s easy to get them. The NestedModules property contains a ReadOnlyCollection of PSModuleInfo objects. Each one has all of the Exported properties of any module, including ExportedCmdlets, ExportedFunctions, and ExportedCommands, which includes all exported command types.

(Get-Module NetAdapter -ListAvailable).NestedModules |
    Format-Table –Property Name, ExportedCommands –Wrap

The ExportedCommands are in dictionaries (like a hash table), so, to get the commands in a given nested module, use a command like this one:

((Get-Module $ModuleName –ListAvailable).NestedModules |
    where Name –eq $NestedModuleName).ExportedCommands.Keys

For example:

PS C:\> ((Get-Module -ListAvailable NetAdapter).NestedModules |
where Name -eq MSFT_NetAdapterQos).ExportedCommands.Keys

Get-NetAdapterQos
Set-NetAdapterQos
Enable-NetAdapterQos
Disable-NetAdapterQos

You can also find out which nested module exports a particular command:

PS C:\> (Get-Module –ListAvailable NetAdapter).NestedModules |
where {$_.ExportedCommands.Keys -eq "Enable-NetAdapterQos"}

ModuleType Version    Name                 ExportedCommands
---------- -------    ----                 ----------------
Cim        1.0        MSFT_NetAdapterQos   {Get-NetAdapterQos, Set-NetAdapterQos, Enable-NetAdapterQos

To get the source file for a nested module, look in the value of its Path property.

PS C:\> (Get-Module NetAdapter -ListAvailable).NestedModules | Format-List Name, Path

Name : MSFT_NetAdapter.cmdletDefinition
Path : C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\NetAdapter\MSFT_NetAdapter.cmdletDef

Name : MSFT_NetAdapterAdvancedProperty.cmdletDefinition
Path : C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\NetAdapter\MSFT_NetAdapterAdvancedPr

Name : MSFT_NetAdapterQos
Path : C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\NetAdapter\MSFT_NetAdapterQos.cdxml
...

And, use the Path value to import the module.

PS C:\> Import-Module $pshome\Modules\NetAdapter\MSFT_NetAdapterQos.cdxml

PS C:\> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Conte
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, C
Cim        1.0        MSFT_NetAdapterQos                  {Disable-NetAdapterQos,

Be sure to test, because many nested modules require other modules.

June Blender is a technology evangelist at SAPIEN Technologies, Inc. and a Windows PowerShell MVP. You can reach her at juneb@sapien.com or follow her on Twitter at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell GUI Debugging Tip: Duplicate Event Handlers

$
0
0

I’m not a professional tester, but I am an expert at making mistakes. I take risks. I try everything. I gravitate to “corner cases” and odd circumstances. That makes me a great amateur tester and, due to a lifetime of experience with breaking things, a pretty good debugger. But, at the Omaha PowerShell User Group meeting in August 2015, I was stumped.

What caused this bug?

David Jones, an Omaha PSUG member and talented PowerSheller, showed me the following code.

$FormGetService_Load = {
    $textboxComputerName.Text = $env:ComputerName
}

Looks perfect. But when he ran his script, on load, the $TextboxComputerName textbox was empty.

image

 

I started by looking for misnamed items. These kinds of errors are typically caused by typos in control names. But all of the control names were accurate.

Then, I looked for any code that might overwrite the value in the textbox. But, the script had no statements that would affect the Text value on load.

I was stumped.

 

When the lab ended, I was very eager to see the code and talk to David. I spent a long time looking through it really thoroughly before I noticed, right at the bottom of the script, a second instance of the form load event handler. This instance had no code in it at all, but it must have been the effective event handler for the form.

$FormGetService_Load = {
}

Apparently, when there are multiple instances of an event handler in a GUI application, the last one takes precedence over the others.

To test my theory, I created a little form with a $LabelStatus label and a $buttonAction button.

image

Then, I added two event handlers to load the form and two event handlers for clicking the button. I had to use copy/paste, because PowerShell Studio tries to prevent you from doing this unintentionally. (Yes, I do this sort of thing. Doesn’t everyone?)

— The first $formTestDups_Load event sets the label text to ‘First load event’. The second one sets the label text to ‘Second load event’.

— The first $buttonAction_Click sets the button text to ‘1st click’; the second sets the button text to ‘2nd click’.

image

When I run my script, the label shows that the second instance of $formTestDups_Load was effective. When I click the button, no matter how many times I click, the button always says ‘2nd click’. Again, the second instance is effective.

 

image

Just to make sure, I reversed the order of the event handlers in the script.

I also added a third event handler for the button that does not set the button text. The third event handler allows me to distinguish between running all event handlers, in which case the button would display ‘1st click’ or ‘2nd click’, or running only the last event handler, in which case it would say “No action,” which is the default.

image

 

Running the script and clicking the button repeatedly verifies that the last event handler for an event is the only effective one.

image

 

Best practice: Don’t add event handlers manually

If you’re using PowerShell Studio, to prevent duplicate event handlers, don’t add them manually. Don’t type or copy an event handler.

Also, if you’re in the middle of editing an event handler and make it invalid (temporarily), and then you run the script, PowerShell Studio will prompt for a missing event handler. If you know that the event handler exists, click Ignore. If you click Insert accidentally, fix the original event handler and delete the duplicate.

And, if the event handler appears to be ineffective, look for a duplicate.

To add event handlers:

  • For default events, double-click the control.

If the event handler for that control exists in the script, PowerShell Studio doesn’t add it again. Instead, PowerShell Studio takes you to the first line of the existing event handler in the script.  (If Options/Designer/Automatically insert default events is checked, PowerShell Studio adds default events for all controls on the form — without double-clicking.)

  • For non-default events, right-click the control and then click Add Events.

image

The Add Events textbox disables events that are already added to the script, so you can accidentally add them again.

image

This was a great lesson for me. From now on, I’ll warn people about typing, copying, or accidentally duplicating event handlers and, when I see a result that doesn’t match the code, I’ll check for duplicates.

Many thanks to the Omaha PSUG for inviting me and to David Jones for his help on this blog post.

June Blender is a technology evangelist at SAPIEN Technologies, Inc. and a Windows PowerShell MVP. You can reach her at juneb@sapien.com and follow her on Twitter at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

Scope in a PowerShell GUI App

$
0
0

If you search the SAPIEN blog, you’ll realize that this is the not our first blog about scope in PowerShell GUIs. In March 2013, SAPIEN CTO Alex Riedel wrote First Rule of PowerShell Scoping Rules, a title that implies the final word in a discussion that wasn’t easy to end. Alex’s blog explained the differences between scoping rules in PowerShell and other languages, like VB Script.

Then, just a month later, SAPIEN Senior Developer David Corrales wrote PowerShell Scoping Revisited, another great post about function scope in PowerShell. A quick search reveals even older posts by Don Jones and Jeffery Hicks.

It seems that everyone is a bit baffled by scopes in PowerShell GUIs and each of us needs to resolve the scope issue that most confounds us. For me, the most baffling part of scoping in a very simple PowerShell GUI app was the lack of an evident scope boundary.

Where is the scope boundary?

I know from about_Scopes and other sources that when a script includes functions, the script is a scope and each function in the script has its own child scope. The child scope can read from, but not change (write to), the values of variables in the parent scope. If you try to write to a parent scope, you create a local variable with the same name.

But, a very simple PowerShell GUI app is just one big script or function. The script contains event handlers, but those seem to be just commands assigned to a variable.

$buttonClick _Close = { $form.Close() }
Is this a scope?

However, when I create a variable that is designed to be shared by the event handlers, the event handlers can read the value, but they can’t change it.

For example, in this little GUI app, the $sharedValue variable is supposed to be shared by all event handlers. The $buttonReadValue_Click event handler reads the value and assigns it to a read-only textbox. The $textboxShared.TextChanged event handler changes the shared value to whatever you type in the text box.

clip_image001

$sharedValue = 'Start'
 
$formTestScope_Load = {
    $textboxShared.Text = $sharedValue
}
 
$buttonReadValue_Click={
    $textboxRead.Text = $sharedValue
}
 
$textboxShared_TextChanged={
    $sharedValue = $textboxShared.Text.Trim()
}

But, it doesn’t work. The $buttonReadValue_Click event handler can read the shared value (and assign it to its textbox), but the $textboxShared_TextChanged event handler doesn’t change it. When you change the value in the Shared value textbox and click Read value again, it gets (and displays) the initial value.

clip_image002

This behaves like a scope issue, but I couldn’t see the scope boundary.

Event Handlers and Script Scope

Then it occurred to me:

Each event handler contains a script block. And, each script block is a script with its own scope.

To prove my theory about the scope boundaries, in the console, I created two variables that contained script blocks. My variables are not event handler, but they have the same syntax.

— The $readScript script block reads a variable value from the parent scope.
— The $writeScript script block changes the value of a variable in the parent scope.

To run the code in the variables that contain script blocks, you need to use the invoke operator (&). The results confirm that each script block is a script that has its own scope. The attempt (in $writeScript) to change the $name variable value fails.

PS C:\> $name = 'PowerShell'
PS C:\> $readScript = { Write-Host "I love $name." }
PS C:\> $writeScript = { $name = 'Windows PowerShell'; Write-Host "I love $name." }

PS C:\> & $readScript
I love PowerShell.

PS C:\> & $writeScript
I love Windows PowerShell.

PS C:\> & $readScript
I love PowerShell.

PS C:\> $name
PowerShell

Next, I’ll scope the variables. I almost never use Global scope. As a best practice, I use the smallest effective scope, but Global is the smallest scope for the command line.

This time, $writeScript changes the value of $name.

PS C:\> $name = 'PowerShell'
PS C:\> $readScript = { Write-Host "I love $name." }
PS C:\> $writeScript = { $global:name = 'Windows PowerShell'; Write-Host "I love $name." }

PS C:\> & $readScript
I love PowerShell.

PS C:\> & $writeScript
I love Windows PowerShell.

PS C:\> & $readScript
I love Windows PowerShell.

PS C:\> $name
Windows PowerShell

The alternative to using a scope modifier (e.g. $global:<varName>), is to use the Set-Variable cmdlet with its Scope parameter.

PS C:\> $name = 'PowerShell'
PS C:\> $writeScript = {
>> Set-Variable -Name Name -Scope Global -Value 'Windows PowerShell'
>> Write-Host "I love $name"
>> }
>>

PS C:\> & $writeScript
I love Windows PowerShell

PS C:\> $name
Windows PowerShell

That works.

Now that I understand that the event handler variables contains scripts with their own scope. Let’s fix the little PowerShell GUI app.

I scoped the $sharedValue variable to the script and, in the $textboxShared_TextChanged event, which is the only place that I change that variable value, I scope the reference to the $sharedValue variable.

$script:sharedValue = 'Start'
 
$formTestScope_Load = {
    $textboxShared.Text = $sharedValue
}
 
$buttonReadValue_Click={
    $textboxRead.Text = $sharedValue
}
 
$textboxShared_TextChanged={
    # scoped variable
    $script:sharedValue = $textboxShared.Text.Trim()
}

Now, when I type in the Shared value box, $textboxShared_TextChanged changes the value of the $sharedValue variable. And, when I click Read value the $buttonReadValue_Click reads the changed value.

clip_image003

In a real script that I plan to save and share, I would explicitly scope all references to a variable in a parent scope, even though it’s not necessary. This makes it very clear that I intended to create a script-scope variable and that I’m referencing a variable in a script scope.

# Script-scoped variables
$script:sharedValue = 'Start'
 
$formTestScope_Load = {
    # scoped variable
    $textboxShared.Text = $script:sharedValue
}
 
$buttonReadValue_Click={
    # scoped variable
    $textboxRead.Text = $script:sharedValue
}
 
$textboxShared_TextChanged={
    # scoped variable
    $script:sharedValue = $textboxShared.Text.Trim()
}

One more consideration. PowerShell Studio encloses every form in a separate function. This structure make it very easy open one form as a modal dialog of another form or share data between forms. However, it makes the scoping one level more complex.

So, this is now the last word about scoping in a PowerShell GUI app. Well, probably not.

June Blender is a technology evangelist at SAPIEN Technologies, Inc and a Windows PowerShell MVP. You can reach her at juneb@sapien.com and follow her on Twitter at @juneb_get_help.

Thanks to Windows PowerShell MVPs Keith Hill and Stephen Owen for their help with this post.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

MVP All Stars in Helsinki

$
0
0

What’s the future of Active Directory? What support can we expect for containers in Windows Server and client? Is PowerShell 5.0 complete?

While most PowerShell scripters are focused on the upcoming PowerShell Summit Europe in Stockholm and PowerShell Asia Conference in Singapore, some of the finest minds were gathering in Helsinki for the MVP All-Stars PowerShell Mini-Summit in Helsinki on 11 September.

Windows IT Pro MVP Sami Laiho organized another in a series of small, intense conferences in the beautiful capital of Finland. I was delighted to be squeezed in at the last minute on my way to Stockholm. These small events are a great experience for speakers and attendees. Unlike larger events, you really get a chance to talk in depth to the speakers and other participants.

MVPAllStars-Helsinki

PowerShell MVP All Stars Helsinki    ©Sami Laiho
L-R: Jeffery Hicks, Jeffrey Snover, June Blender, Aleksandar Nikolic, Don Jones

 

The Talks

Jeffrey Snover, the inventor of PowerShell and now a Technical Fellow at Microsoft, opened the conference with a broad overview of the past, present, and future of Windows Server in the IT ecosystem, stressing how the recent move in server development is driven by cloud integration, the critical role of PowerShell in server management and automation, and the evolution of Nano Server, the tiny pearl of a Windows Server with no GUI.

Don Jones of Pluralsight brought lessons from his experience with the PowerShell Verified Effective Exam on advanced functions. Although ~40 people sat of the exam, only one passed. Yes, one. The exam wasn’t particularly difficult, but the graders were looking for best practice coding and evidence of clear understanding of the task and the language. They suspect that many failed because they were accustomed to copying and using PowerShell scripts without truly understanding the purpose of various elements of the language.

A few lessons:

  • — Be sure that you understand what you’re doing. Don’t just use what you’ve seen or read about.
  • — Use standard parameter names and approved verbs
  • — Don’t use SupportsShouldProcess (WhatIf, Confirm) unless the function is potentially risky. If you’re writing a Get-* function with SupportsShouldProcess, you’re probably using the wrong verb.
  • — All advanced functions should have some basic help. And, make sure that Get-Help displays your help. A single typo in any comment-based help keyword causes Get-Help to ignore the help.
  • — To enable piping to a parameter that takes multiple values, use Begin/Process/End for piped values and ForEach for a collection of parameter values submitted at the command line.
  • — Don’t return more than one object type. If you need properties of different objects, create a custom object.
  • — If parameter values are limited to a particular set, use the ValidateSet attribute.

 

Aleksandar Nikolic of PowerShell Magazine fame presented a great introduction to communicating with Nano Server, including using WinRS, a CIM session, and a Windows PowerShell session WinRM/PSSession. There’s a small, but growing, set of modules on Nano Server, including most of PowerShell Core, and you can use some local modules on your Nano Server remotely. Aleksandar also demonstrated how to use the new remote debugging features in PowerShell 5.0 to debug a script on a Nano Server (Wait-Debugger, Get-Runspace, Get/Enter-PSHostProcess), how to use the new (yet undocumented) ToSession and FromSession parameters of Copy-Item to copy files to a Nano Server a remote session, and how to use the VMName, VMGuid parameters of Invoke-Item to test commands on a Nano Server in a VM.

Jeff Hicks of Pluralsight finished off the talks with a nice review of Scheduled Jobs in PowerShell 3.0, including triggers, scripts and script blocks, and scheduled job options.

Ask the Experts

The day concluded with a great Q/A where folks who hadn’t yet had a chance to ask the tough questions got to ask the panel. And the answers were as complex as the questions, often drawing conflicting responses, especially about predictions.

On Future of Active Directory, Don Jones believes that, while it’s an excellent tool for on-premises domains, as we move to the cloud, even a hybrid cloud, its use cases will dwindle over time. “We’ll look back in 10 years and say that AD was a great technology for its time.” Jeffrey Snover disagreed, at least about the pace of that change and argued that AD will be used and improved in on-premises server management for many more years.

Is PowerShell 5.0 complete? After Windows 10 released with a version of PowerShell 5.0 that was still in preview, and following the release of a fully-supported WMF 5.0 Production Preview for systems earlier than Windows 10, that PowerShell 5.0 was not, and perhaps, would never be finished, closed, or complete, in the way that earlier version of PowerShell were. Jeffrey Snover argued that this assumption was false and that PowerShell 5.0 would be completed and stable in Q42015. At that point, they would start working on a new version of PowerShell. PowerShell is, of course, continuously evolving, but there will be a point at which PowerShell 5.0 will be complete and further changes will go into a new build.

A question about support for Containers in Windows Server showed the depth of the panel and audience. Jeffrey Snover acknowledge that containers, which let you isolate the deployment of an application and its dependencies in an abstraction layer, are a “disruptive technology.” He talked about support for containers that’s already in Windows Server, and he encouraged participants to learn about them, but didn’t really think that any of the current use-case scenarios were that compelling. Don Jones put the discussion in perspective, reminding participants that Application Virtualization (App-V) in Windows has been providing similar support for isolated applications, but hasn’t been widely used.

 

In summary, it was an excellent day and, I hope a worthwhile day for attendees. In broader perspective, it demonstrated the value of small hybrid (in-person and online) technical conferences, especially as part of a series.

June Blender is a technology evangelist at SAPIEN Technologies, Inc and a Windows PowerShell MVP. You can reach her at juneb@sapien.com and follow her on Twitter at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell Studio 2015: Service Release v4.2.94 and Projects with Folders

$
0
0

We released a new service build for PowerShell Studio 2015 (v4.2.94).

Here’s what’s new:

Folder Support in Projects

PowerShell Studio 2015 projects now support folders. The project folders reflect the folder structure of the project files. Therefore if you previously organized your project files in folders within the project’s directory, those folders will automatically be displayed in the Project Panel once the project is loaded.

image

Using folders within projects makes it easier to organize projects with large amounts of files.

With the new folder feature, you can now place your module help files in respective language specific folders:

image

Important: Once PowerShell Studio updates the project file, you will no longer be able to open the project using older builds of PowerShell Studio. A backup of the project will be created before updating.

Adding Folders

You can add folders by press the “New Folder” button in the Project Panel:

Add a new folder using the Project Panel's menu.

Or you can add a new folder using the Project Panel’s context menu:

Use the context menu to create folders and files.

The new folder will be created under the selected folder:

Create nested folders.

Renaming Folders

You can rename the folder by clicking twice on the node in the project panel or using the Rename command in the context menu:

Rename the folder in the

Alternatively you can use the Property Panel to rename the folder:

Set folder name in Properties Panel.

Moving Files and Folders

You can move files and folders simply by dragging and dropping them within the Project panel:

Drag File Drop in the desired folder. The file is now moved to the new location.

Important: To rename or move files you must use the Project Panel instead of Windows File Explorer, otherwise the project’s references will point to incorrect paths.

 

Designer Updates

We added new commands to the designer:

image

Equalize Vertical Space – Makes the vertical distances between the selected controls equal.

Before After

Equalize Horizontal Space – Makes the horizontal distances between the selected controls equal.

Before

After

 

We added a new Properties command to the designer context menu:

Properties command in designer context menu.

The Properties command will display the control in the Properties Panel and if closed, displays the panel.

 

We surfaced the AllowDrop property of the GUI controls in the Properties Panel:

image

You need to set this property to True if you want to allow your controls to accept Drag and Drop requests.

Note: AllowDrop requires the script to run in STA mode.

 

New Control Set

We added a new control set “ComboBox – Countries” which inserts a combo box populated with a list of countries.

image

 

Activation Issue Resolved

This service build resolves an activating issue caused by specific characters in user password.

Please refer to the following article for more details:

https://www.sapien.com/blog/2015/07/29/software-activation-issues/

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

Hidden Charms of PowerShell Studio

$
0
0

I’m coming up on my one-year anniversary at SAPIEN Technologies, Inc. and my one-year anniversary of using PowerShell Studio as my primary IDE. When I speak at conferences and user groups, I don’t typically talk about products, because people don’t want to hear “vendor talks.” But, in private, I’ve become a total PowerShell Studio fan-girl. It’s a bit embarrassing, honestly.

I love the big powerhouse features, like PowerShell GUI automation, .EXE and .MSI creation, the Function Builder and Parameter Builder, and New Module from Functions. But, it’s the smaller, quieter features that have me hooked. Here’s my list of can’t-live-without-’em features of PowerShell Studio. Do you have a different list? Share in the comments below.

10. Expand all aliases

I’m a huge proponent of Windows PowerShell best practices, but like everyone else, my instinctive behaviors don’t always meet my coding standards. Before I share any script or function, or even a code sample, I press Ctrl + Shift + A, to replace all cmdlet, function, and parameter aliases with their correct full names.

The new Qualify Cmdlet Names feature (Ctrl+Shift+H) is a great addition, too, especially with the proliferation of cmdlets and modules in open source.

9. Generate comment-based help

It’s predictable that I would love this feature. What’s less predictable is how often I use it. Like all the time.

I jump in, write my function, add parameters, and then right-click and click Generate comment-based help. It parses my code and adds starter help, including help for my parameters. Comment-based help is error-prone; one typo in a keyword causes Get-Help to ignore the whole comment block , so I really rely on my tools, including this feature, to avoid errors.

8. Snippets with variables and help

Lots of tools have snippets, but I’ve never seen one with better support for variables and help in snippets. I use the tooltip/help feature in PowerShell Studio snippets to remind me to do things that I might otherwise forget, like adding quotation marks to PSCustomObject hash table values.

clip_image002

7. Parameter set history

PowerShell Studio maintains a history of the parameter sets that you run. And, it maintains a separate history for the Run and Debug command series.

Good code-coverage testing depends on testing parameter combinations. Before I had the parameter history, I used all sorts of tricks to remember the parameters that I tested, including filling pages of OneNote with notes that were tough to decipher. Now, PowerShell Studio just does it automatically.

clip_image004

6. Spotlight articles

TechNet is useful. So is MSDN. But, there’s nothing like a reference that is specific to the current task. When I’m building a PowerShell GUI app, the SAPIEN Spotlight articles are my go-to reference. They describe the control, its default event, and most commonly used properties.

They’re brief, clear, designed for GUI beginners, and the examples are all PowerShell, not C# or VB. I like the Spotlight articles so much that when I have an extra minute, I click a random control and read its spotlight article to give me ideas for my next PowerShell GUI app.

clip_image005

By the way, the Spotlight articles are the work of SAPIEN Senior Developer David Corrales. If you like them, next time you see David, be sure to thank him.

5. Restart shell

The Restart shell feature of the Console pane kills the PowerShell process that’s running in the Console pane and starts a new process. This lets me test and retest (and retest) my features without disturbing the code in my Editor pane or interrupting my work.

When I demonstrate features, I restart the console often, sometimes to emphasize that elements of the code are independent, but most often to keep items saved in the session, like variables, functions, and classes, from affecting the result of the next command.

clip_image006

4. Run and Run in console

The Run in Console feature doesn’t just run a script in the Console pane — it dot-sources it. Dot-sourcing adds the items in the script scope, including function, script-scoped variables, classes, and workflows, to the console, so they’re available even after the script completes.

clip_image007

This feature is fantastic for testing and demonstrations, because after running the script, it lets you use and test the script elements in different ways and examine the effect of the persistent elements on the environment.

Run is really different. It’s the epitome of best-practice testing. Run creates a new session that never includes local artifacts, like your Windows PowerShell profile, or session-specific items, like variables, and then runs the script in the clean-slate session.

I use both Run and Run in Console continuously. I can’t imagine a scripting environment that didn’t have both tools.

3. Copy HTML

If you blog, the Copy HTML feature is your friend. For me, it’s a best friend. I used to fiddle with <pre> tags and plugins. Now, when I want to include code in a blog post, I right click the code in PowerShell Studio, click Copy HTML, and then paste the HTML for the code in the Text view of the post. The result is perfectly copied code, including color coding and formatting.

clip_image009

2. File groups

For presentations and demos, for testing and spec reviews, you often have multiple files to display. And, you don’t want to start finding and loading the files at the last minute.

PowerShell Studio lets you create a filegroup, which is, essentially, a list of files in a specified order that you open in a single click. The files don’t need to be in the same location, or on the same computer.

When you’re ready to present, you just click the file group. PowerShell Studio opens the files and displays them in the specified order. Whew!

And, adding files to a file group doesn’t change the constituent files or their filenames, so it doesn’t affect the presentation at all. Stellar feature.

1. Format Script button

The one PowerShell Studio feature that I can’t live without is not the Update-Help button, which I love, or the Watch window in the debugger, which keeps me sane. Instead, it’s the Format Script button.

Good formatting isn’t just a visual aid. It also helps me to recognize, avoid, and eliminate errors. When I’m coding, especially refactoring, and my script indentation or line breaks become inconsistent, I don’t have to start tabbing or spacing, or looking for enclosure matches. I just click Format Script.

 

PowerShell Studio makes me efficient and productive. I rely on the major features all the time, but it’s the tiny hidden charms that make my life easier and make me a better and more professional coder.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell Studio 2015 – Find References and File in Files Update

$
0
0

We just released another build of PowerShell Studio 2015 (v4.2.95). We included a few new features to this build, but we will focus on the search-related features in this particular article.

 

Find in Files Update

We added some new options to the “Find In” pull down list of the Find in Files dialog.

Find in Files

The new options include:

Current Document – Searches in the current document only.
All Open Documents –Searches in all the open documents.
Current Project – Search in all the project files.

These new options will allow you to narrow your search to the files you are currently working on. For example, you can conduct a search using a regular expression to find all the variables within the current file:

Regular Expression search in current document.

And the results are listed in the Find Results panel:

Find Results

As opposed to the normal Find feature, which selects the current search result only.

Find All References

We added a new command to the editor’s context menu: Find All References.

Editor's context menu.

Find All References builds upon our existing reference highlighting feature. In addition to highlighting all the references, it will list all the references in the Find Results panel:

Find all references.

This makes it easier for you to navigate between references. Whenever you double-click on a reference in the panel, the Find Results panel will mark the reference as visited:

Find Results marks visited references.

If you are working with a project, the references located in other project files will also be listed in the search results. We hope that the new Find All References command will make it easier to maintain your existing scripts.

 

 
Next we will discuss the new additions to the Custom Menu.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell Studio 2015 – New Custom Menu Features & GIT template

$
0
0

We are continuing to cover the new features introduced in the latest service build of PowerShell Studio 2015 (v4.2.95). In this article we will cover the new additions to PowerShell Studio’s custom menu.

image

For those who aren’t familiar with the custom menu, it is a menu that users can customize to call other tools and processes. The menu’s contents can be determined on a global level or a local folder level. Please refer to the following article for more details on the custom menu feature:

https://www.sapien.com/blog/2013/01/08/powershell-studio-2012-with-git-subversion-and-mercurial-oh-my/

 

Application vs Commandline

We added an optional [Application] group to the CustomMenu.inf.

Application group

Any command in the [Application] group will run without waiting for the process to complete. This is a fire-and-forget trigger for applications that do not provide console output, such as PowerRegEx or Windows Explorer.

 

If you want to display the console application’s results in the Output panel, use the Commandline group:

Commandline group

Note: [Commandline] is the same as using [Menu].

The [Application] and [Commandline] groups are separated in the custom menu.

 

Menu Separators

We included the ability to add separators to the custom menu, which allows you to visually group commands:

Custom Menu with separators

To add a separator, include a line item with a dash for text:

Add a separator

 

 

Prompt for Input

You now have the option to prompt for input when triggering a custom menu item.

For example, when committing in GIT, you are required to insert a comment. Now you can use the prompt to enter a unique comment.

Prompt

To prompt the user, you must use the following macro in your Custom Menu.inf file:

{Prompt}

If you wish to include a message then use the following format:

{Prompt|Message}

Where Message is the text you wish to display.

If you wish to include a default value then use the following format:

{Prompt|Message|Default Value}

Where Default Value is the text you wish to prefill the prompt dialog’s input line.

Here is a sample prompt that is used to enter a comment for the GIT commit command:

Using a prompt

As you can see, macro variables can be used within the prompt’s text.

 

GIT Custom Menu Template

You can download our sample Custom Menu.inf and use it as a template for your GIT repository folders. Simply copy the Custom Menu.inf into your GIT folder and edit the template to fit your needs. When you open a file in the folder, PowerShell Studio’s custom menu will automatically provide you with the commands you specified.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

What’s new in iPowerShell Pro?

$
0
0

Build 5.0.133 of iPowerShell Pro has just been released. This build primarily covers iOS 9 compatibility with some bug fixes and performance increases. But we did slip in a very interesting and future oriented feature: the ability to connect to PowerShell remotely via SSH!

In June of 2015, the PowerShell team announced that they were going to embrace SSH connectivity to PowerShell via OpenSSH. This is exciting news for many in the community. Of course, we wanted to get a head start on supporting this ability, but how do we support something that has not yet been released?

As this article states, there are SSH solutions already out there. For this feature, SAPIEN has worked with /n Software to connect to their PowerShell Server product which allows connecting remotely to PowerShell via SSH. Its a great solution that actually works TODAY!

SSH connections to PowerShell in iPowerShell Pro are created the same way PSWA connections are created. A new field has been added to the “Add Server” screen that allows you to select between PSWA and SSH. When you select SSH, the Auto Login and Server fields disappear. The location field prompts for an IP address rather than a URL and the default port prompt changes from 443 to 22.
Adding an SSH connection.

Adding an SSH connection.

SSH servers are clearly differentiated from PSWA servers on the Servers screen by the letters “SSH” instead of “PSWA” on the server icon.
PowerShell SSH and PSWA Servers.

PowerShell SSH and PSWA Servers.

Interacting with a PowerShell session works just as expected. All of the iPowerShell Pro features: Build, History and Scripts also work as you are used to.
Connecting to a PowerShell SSH session using iPowerShell Pro.

Connecting to a PowerShell SSH session using iPowerShell Pro.

All-in-all, it is a seamless and easy way to interact with PowerShell on a server. Try it out!

/n Software offers a free single connection license for their PowerShell Server product.

We will keep out ears open for when OpensSSH comes to PowerShell and make sure that everything works there as well.
P.S. Since this is a basically SSH, it actually works for any kind of SSH connection. Give it a try!
 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

Why Do We Need Constructors?

$
0
0

While traveling after PowerShell Summit Europe in Stockholm, I was honored to be the guest of the Microsoft Technical User Group in Oslo, Norway (@MTUG_Norge). This well-established user group meets on the beautiful campus of the University of Oslo, a short light-rail ride from downtown Oslo.

We got together for a hands-on lab on classes in PowerShell 5.0. It was an experienced group — mainly IT operations folks — who well-versed in PowerShell. The concepts are all new, but the group of 35-40 people were quick to understand them.

One thoughtful guy asked a particularly good question: Why do we need constructors? As PowerShell scripters, we’re used to the New-Object cmdlet and creating objects with PSCustomObject, PSObject, and hash tables. Why do we need yet another concept in object creation?

Why Constructors?

The short answer is that, unbeknownst to us, we’ve been using constructors all along. But, in its quest to make us successful, PowerShell has (mostly) hidden the concept from us.

A constructor is a special method of a class that initializes new objects or instances of the class. Without a constructor, you can’t create instances of the class. Imagine that you could create a class that represents files, but without constructors, you couldn’t create any files based on the class.

Some types of classes, including abstract classes and interfaces, don’t need constructors, because you don’t create instances of them. Instead, you use them as base classes and derive subclasses from them.

(Cool digression: Abstract classes aren’t required to have constructors, but they can have them. You can call the constructor of an abstract class to create a new instance of a subclass that’s based on (“derived from”) the abstract class. Thanks to Doug Finke for his excellent tutelage.)

(Fun fact: You can implement multiple interfaces, but you can derive a class from only one base class.)

How do you use a constructor?

Even though constructors are methods, you don’t call them directly.

Instead, constructors determine the parameter values or “arguments” that you are required to provide to the New-Object cmdlet or the New static method.

For example, let’s create a Tree class that has two properties, Species (a string) and Height (an integer).

class Tree {
    [String]$Species
    [int32]$Height}

The Tree class also has one constructor that takes one string value (for the species) and one integer value (for the height).

# In Help: Constructor1: [String]$Species, [Int32]$Height

When you create a tree, you must provide precisely one string and one integer in the specified order. (The order matters because you don’t type parameter names.)

New-Object -TypeName Tree -ArgumentList 'Mimosa', 10

-or-

[Tree]::New('Mimosa', 10)

This works:

Species Height
------- ------
Mimosa 10

If you try to create a Tree with missing, extra, or different objects, the command fails.

PS C:\> New-Object -TypeName Tree -ArgumentList 10

New-Object : Cannot find an overload for "Tree" and the argument count: "1".
At line:1 char:1
+ New-Object -TypeName Tree -ArgumentList 10
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

How do I write a constructor?

Constructors initialize the new object, that is, they set the startup property values for the object. They might also do other things necessary to make the object usable.

You can distinguish constructors from other methods of a class because constructors always have the same name as the class. If the class is Tree, it’s constructors are all named Tree, too.

A constructor is a method, so it has a script block and (optional) parameters.

Syntax:

 ( [] ) {
 
}

For example, the Tree class has a constructor that takes a Species string. Like the class, the constructor is named Tree.

Tree ( [string]$Species ) {
    $this.Species = $Species
}

You can have multiple constructors. But, because the parser looks only at parameter types, not names, the constructors must take different types.

This constructor in the Tree class takes a string and an integer. It assigns the string to the Species property and the integer to the Height property.

Tree ( [string]$Species, [int32]$Height ) {
 
    $this.Species = $Species
    $this.Height = $Height
}

Here is the tree class with its Tree constructors.

class Tree ()
{
 
    [String]$Species
    [int32]$Height
 
    # Here is a constructor. Notice the name.
    Tree ( [string]$Species ) {
        $this.Species = $Species
    }
 
    # Here is another constructor. It's also named Tree, but it takes different parameter types.
    Tree ( [string]$Species, [int32]$Height ) {
        $this.Species = $Species
        $this.Height = $Height
    }
 
    # Here is a different method with a different name.
    [int32] Grow ( [uint32]$Amount) )
    {
        $this.Height += $Amount
        return $this.Height
    }
}

Constructors don’t return anything. A return type is not permitted.

To use the first constructor, I need to submit a string, such as ‘Mimosa’.

New-Object -Typename Tree -ArgumentList 'Mimosa'

-or-

[Tree]::New('Mimosa')

To use the second constructor, I submit a string and an integer, in that order.

New-Object -Typename Tree -ArgumentList 'Mimosa, 10'

-or-

[Tree]::New('Mimosa', 10)

How do I find the constructors of a class?

The simplest way to get the constructors in a class is to use the New static property of all classes.

The syntax is:

[]::New

For example, to get the constructors in the Tree class:

PS C:\> [Tree]::New

OverloadDefinitions
-------------------
Tree new(string Species)
Tree new(string Species, int Height)

Must I write a constructor?

Surprisingly, the answer is no.

When you create a class, Windows PowerShell creates a default constructor for you. A default constructor has no parameters and takes no arguments or values. You might hear it called a null constructor or parameter-less constructor.

For example, if I create a Tree class with nothing in it, I can create a Tree object.

PS C:\> class Tree {}
PS C:\> $myTree = New-Object -TypeName Tree
PS C:\> $myTree | Get-Member

   TypeName: Tree

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()

If you use the New static property of the Tree class, you can see the default constructor that Windows PowerShell created for you.

PS C:\> [Tree]::New

OverloadDefinitions
-------------------
Tree new()

However, if you add a constructor to the Tree class, the “free” default constructor disappears.

PS C:> class Tree {
>> Tree ([String]$Species) {}
>> }
>>
PS C:\> [Tree]::New

OverloadDefinitions
-------------------
Tree new(string Species)

If you want a default constructor in your class, you need to add it explicitly. (And, you should, because it allows people to use hash tables to create objects. I’ll explain in detail in a later blog post.)

PS C:\> class Tree {
>>
>> Tree () {}
>> Tree ([String]$Species) {}
>> }
>>
PS C:\> [Tree]::New

OverloadDefinitions
-------------------
Tree new()
Tree new(string Species)

 

Constructors are very new to Windows PowerShell users, but we’ve been using them whenever we use the New-Object cmdlet, and Windows PowerShell has been using them to create objects whenever we use a Get cmdlet. Now, in Windows PowerShell 5.0, we can create them, as well as use them.

Thanks again to MTUG_Norge and its member for having me. I really enjoyed it.

June Blender is a technology evangelist at SAPIEN Technologies, Inc and a Windows PowerShell MVP. You can reach her at juneb@sapien.com and follow her on Twitter at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

Using Module-Qualified Cmdlet Names

$
0
0

Open-source projects and new methods of distributing modules, such as PowerShellGet and the PowerShell Gallery, have significantly increased the availability of Windows PowerShell modules. While we once relied on modules from Microsoft, we now can select from hundreds of new modules developed in the community.

The upside of having so many modules is vastly increased utility. But, all of those new modules make cmdlet and function name conflicts more likely. Many modules use prefixes, but some are likely to slip through.

To be sure that you’re using the cmdlet or function that you selected, and not a different one with the same name, use a module-qualified cmdlet name. This is valuable if you write scripts and modules, and critical if you share them, where they might run on a system with a module set that you cannot anticipate.

PowerShell Studio has a new feature that qualifies all of the command names in your script. You can turn it on before you share a script and, if you choose, turn it off. PowerShell Studio also recognizes module-qualified names and uses syntax coloring to indicate when a command is correctly qualified.

Module-qualified names were introduced in Windows PowerShell 3.0.

Module-Qualified Cmdlet Names

To specify the module of a function or cmdlet, use the following syntax:

[ModuleName]\[Cmdlet_or_Function_Name]

For example, to specify the Get-Process cmdlet in Microsoft.PowerShell.Management, type:

Microsoft.PowerShell.Management\Get-Process

The module prefix is valid in any command. For example:

Microsoft.PowerShell.Core\Invoke-Command -Session $s -ScriptBlock {Microsoft.PowerShellCore\Save-Help -Path D:\HelpFiles}

You can also use module-qualified commands in splatted parameters. For example:

$s = Microsoft.PowerShell.Core\New-PSSession -ComputerName VMSvr01
 
$Params = @{Session=$s; ScriptBlock={Microsoft.PowerShell.Management\Get-Process}}
 
Microsoft.PowerShell.Core\Invoke-Command @Params

PowerShell Studio Support for Module-Qualified Commands

Beginning in Version 4.2.90, PowerShell Studio recognizes and supports module-qualified commands.

· To qualify all of the commands in your script, type Ctrl + Shift + H.

image

· To remove the module qualification from all commands in your script, type Ctrl + Alt + H.

image

Also, if you type a module qualified name for a particular cmdlet, and that module does not have a cmdlet with that name, such as a Get-Command command in the Microsoft.PowerShell.Utility module, PowerShell Studio labels it as “unknown.”

image

If you type a correct module qualification, PowerShell Studio recognizes it and colors it blue (or the color specified for cmdlets names in your Option settings).

image

Name Conflicts in Windows PowerShell

When two commands have the same name (and neither is module-qualified), the Windows Powershell command precedence rules determine which command runs. The precedence rules are documented in about_Command_Precedence, but, in short, the precedence order is:

1· Alias
2· Function
3· Cmdlet
4· Native Windows command

When commands with the same name have the same type, Windows PowerShell runs the command that was added to the session last. Because that is arbitrary and not predictable, it’s best to qualify the command name.

In Windows PowerShell 5.0, you can also install different versions of the same module in the same or different directories (and scope) on the same computer. It would be very useful to be able to qualify the version, as well as the module, of a command, but that’s a subject for a different blog post.

June Blender is a technology evangelist at SAPIEN Technologies, Inc and a Windows PowerShell MVP. You can reach her at juneb@sapien.com and follow her on Twitter at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

Creating Objects in Windows PowerShell

$
0
0

Applies to: PowerShell 5.0.10240

I was recently in the beautiful city of Copenhagen, Denmark, where I was the guest of PSUG.DK, PowerShell User Group in Denmark. We met in the swanky Microsoft offices for a hands-on about classes in Windows PowerShell 5.0.

image

Microsoft Offices, Copenhagen, Denmark.

In the hands-on lab, we create a class, create instances of the class, and add constructors, properties and methods. Then, we try some of the more advanced features, like static properties and methods, inheritance, and interfaces.

To keep the class in a reasonably brief, when we create objects, I show New-Object and the New static method of objects, but gloss over creating objects from hash tables. In this blog post, I’d like to introduce all three methods and explain how to use them.

Creating Objects at the Command Line

There are (at least) three ways to create an object in Windows PowerShell. The first two techniques depend on the constructors defined in the class. The third one, hash tables, requires only a default constructor, that is, a constructor that has no parameters and takes no arguments or values.

For more information about creating objects in Windows PowerShell, see about_Object_Creation.

About constructors

Constructors are special methods that initialize the objects in a class. The constructors of a class determine which property values you need to specify in order to create a class.

One type of constructor is particularly important. It’s called a default constructor, although it’s often known as a null constructor or parameter-less constructor. A default constructor has no parameters and takes no arguments or values. It’s defined like this:

<className> ( ) { }

I’ll create a Tree class with Species, Height, and Deciduous properties. The Tree class has a default constructor (one with no parameters), a constructor that takes a Species string and a Height integer, and a Grow method.

class Tree {
 
    [String]$Species
    [int32]$Height
    [Boolean]Deciduous = $True
 
    Tree () {}
    Tree ([String]$Species, [int32]$Height)
    {
        $this.Species = $Species
        $this.Height = $Height
    }
 
    [int32] Grow ([int32]$Amount)
    {
        $this.Height += $Amount
        return $this.Height
    }
}

To find the constructors of any class, use the New static property of all classes. For example, to find the constructors of the Tree class, type:

PS C:\> [Tree]::New

OverloadDefinitions
-------------------
Tree new()
Tree new(string Species, int Height)

The result shows that you can create a Tree object with no parameters or with a string and an integer (in that order).

A constructor is a method, so when you use it, you do not specify parameter names and you must specify the values in the order that they are defined in the constructor. If you don’t, the command fails.

Constructors are special in two ways:

  • They have the same name as the class.
  • You don’t call them directly. Instead, you use a technique that takes a constructor, like the New-Object cmdlet or the New static method.

For more information about constructors, see about_Classes and Why Do We Need Constructors?

Use the New-Object cmdlet

To create an instance of a class with the New-Object cmdlet, use the following syntax:

New-Object -Typename <ClassName> -ArgumentList <Constructor>

To use a constructor, enter the values that the constructor specifies in a comma-separated list. Do not include any parameter names.

For example, to create a Tree with the following constructor, you need to enter one string and one integer.

Tree new(string Species, int Height)

Example:

PS C:\> $myTree = New-Object -TypeName Tree -ArgumentList 'Maple', 10
PS C:\> $myTree

Species Height Deciduous
------- ------ ---------
Maple   10     True

If you enter a different number of values, or values of a type that cannot be converted to the specified type, the command fails.

PS C:\> New-Object -TypeName Tree -ArgumentList 10, 'Maple'

New-Object : Cannot convert argument "1", with value: "Maple", for "Tree" to type "System.Int32": "Cannot convert value "Maple
"Input string was not in a correct format.""
At line:1 char:1
+ New-Object -TypeName Tree -ArgumentList 10, 'Maple'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

The Tree class also has a default constructor — one with no parameters. To create a Tree object with the default constructor, just omit the ArgumentList parameter. Then, you can assign values to the properties individually.

PS C:\> $myTree = New-Object -TypeName Tree
PS C:\> $myTree

Species Height Deciduous
------- ------ ---------
0 True

PS C:\> $myTree.Species = 'Maple'
PS C:\> $myTree.Height = 10
PS C:\> $myTree.Deciduous = $True

Use the New static method

You can also use the New method to create an object. (The method isn’t new. That’s its name.) The New method is a static method — a method of a class, not a method of an object — so you use the syntax with two consecutive colons (::) to call it.

The New method typically requires less typing than New-Object, but it’s a bit less familiar to PowerShell users.

To use the new method to create an object, use the following syntax:

[<ClassName>]::New(<Constructor>)

Again, when using a constructor, enter the values that the constructor specifies in a comma-separated list. Be careful to enter the values in the order that the constructor specifies. Do not include any parameter names.

For example, to create a Tree object with the following constructor:

Tree new(string Species, int Height)

Type:

[Tree]::New('Maple', 10)

To use the default constructor, leave the parentheses empty. They’re still required to distinguish the New method, which creates a new object, from the New property, which stores the constructors.

[Tree]::New()

Use a Hash Table

A hash table is a very convenient way to create an object. Although it typically requires more typing than using New-Object or the New static method, you don’t have to use a particular constructor.

Because you specify parameter names, you can specify the values in any order. (The keys in a hash table are unordered by definition, so the order cannot matter.)

However, this method works only when the class has a default constructor, that is, a constructor with no parameters. And, the properties that you specify in the hash table must be “settable,” that is, they cannot be read-only.

For example, the Tree class has a default constructor.

PS C:> [Tree]::New

OverloadDefinitions
-------------------
Tree new()     # <------------------------ This is the default constructor
Tree new(string Species, int Height)

To create an object with a hash table, use the following syntax:

[ClassName]@{<Parameter>=<Value>; <Parameter>=<Value>...}

For example:

[Tree]@{Species='Maple'; Height=10}

However, you can also create a hash table that does not match a constructor. And, because you specify the parameter names, the order of the values does not matter.

These commands work, too. The property values that you don't specify are left undefined.

[Tree]@{Height=10; Species='Maple'}
[Tree]@{Deciduous=$True; Height=10; Species='Maple'}
[Tree]@{Species='Maple'}

Hash Tables and PowerShell Classes

Hash tables are so convenient that many argue that they should be the primary way of creating PowerShell classes.

They are also particularly well-suited to PowerShell classes, because Windows PowerShell adds a default constructor automatically to every class.

PS C:\> class AnyClass {}
PS C:\> [AnyClass]::New

OverloadDefinitions
-------------------
AnyClass new()

When you create your own constructor, the default constructor disappears and you have to recreate it.

Thus, several people have argued that you should not create constructors in a PowerShell class. You should just leave the default constructor and let uses create objects with hash tables.

I think this is a good general practice, but there might be cases where you want to require that every instance of a class has a particular property value. In that case, you need to omit the default constructor and create only constructors that include the required property value.

So, there you have it. You can create classes and instances of those classes. Thanks again to Claus, Heine, and all the fantastic PowerShell folks in Denmark.

June Blender is a technology evangelist at SAPIEN Technologies, Inc and a Windows PowerShell MVP. You can reach her at juneb@sapien.com and follow her on Twitter at @juneb_get_help.

 

 
[Google+] [Facebook] [LinkedIn] [StumbleUpon] [Digg] [Reddit] [Google Bookmark]

PowerShell HelpWriter – Service Release v1.0.16

$
0
0

In the latest service release of PowerShell HelpWriter 2015, you will notice a few changes to the Select Module dialog that appears when creating a new help file.

image

The updated dialog includes several new features.

 

Sorting Modules

The module list can now be sorted by clicking on the respective column headers. In addition, we now added a new column that displays the module’s company information.

image

 

 

Filtering Modules

 

Tired of scrolling down a long list of modules? No more. You now can filter the modules by company using the new drop down list:

image

Choose to display all the modules, non-Microsoft modules, or modules created by a specific company:

SNAGHTML6437cbe

 

 

Browse for Module

Previously PowerShell HelpWriter 2015 required that your module be placed in a discoverable location defined by the environmental variable PSModulePath. With the new browse feature, this is no longer the case. Now you can click on the Browse button in the Select Module dialog and select the module manually.

image

 

 

Default Save Location

We changed the default save location for generated help files so that it defaults to the location that PowerShell requires. PowerShell HelpWriter will now create and set the default save location to the “en-US” language specific folder located in the same directory as the module.

 

Commented Information

For your convenience, we now include commented information that contains the name of the module and the version used to generate the help file.

image

 

Please continue providing your feedback. Many of the new features included in the service builds are suggestions from users like you. Therefore if you have any suggestions or feature requests, please share them with us on our Wish List and Feature Requests forum.

 

 
[Google+]   [Facebook]   [LinkedIn]   [StumbleUpon]   [Digg]   [Reddit]   [Google Bookmark]  

PowerShell Studio 2015: Service Release v4.2.96

$
0
0

We released a new service build for PowerShell Studio 2015 (v4.2.96).

 

In this release we introduced another new feature:

 

Create Module from Help

If you aren’t familiar with PowerShell HelpWriter, it is a tool that lets you create external PowerShell help files (MAML) for existing modules or from scratch. PowerShell HelpWriter can be a useful design tool for creating modules, by allowing you to plan out your module’s cmdlets and its parameter sets before writing a single line of PowerShell code.

This write-help-first design approach is made much easier with PowerShell Studio’s Create Module from Help File feature.

image

Create a new project and select the help file and give your module a name:

SNAGHTML108e6ab

Now you have a new module containing the help file and the skeleton functions defined in the help file.

image

 

Build Button for Module Projects

We added a build button to the Project Panel for module projects.

image

The build button will build the module and export the module to:

My Documents\WindowsPowerShell\Modules

 

Improved Syntax Coloring for Classes

We improved syntax coloring for classes. Enumerator and class types are now colored.

image

Support for New Operator

We also added PrimalSense support for .NET types and the New operator that was introduced in PowerShell V5.

image

Improved Theme

We improved the theme coloring of the panels and buttons (especially for those who like the dark theme):

image

 

Packager Engine Parameters Update

We made some changes to the packager engines so that it is easier for you to handle parameters. Now when you have a parameter block in your script, you can pass named parameters to the executable and it will pass the values to the script for you.

For example, if your script has a parameter block such as:

  param($param1 = 'default', [int]$param2, [int]$param3)

You can call the packaged executable using named parameters:

  packaged.exe –Param1 "value 1" –Param2 2 –Param3 1

Now there are a few caveats:

1. Arguments/ Parameters passed to the executable are going to be strings and not the original objects. Luckily PowerShell can convert strings to integers and other types behind the curtains.

2. You can’t pass an array of values:

       -Param1 1, 2, 3

Instead you will have to convert it to a string and process the values in your script.

       -Param1 "1, 2, 3"

Then to have to split the value:

       $param1 –split ','

3. You can’t use switch or Boolean parameters. Instead you will have to use a parameter of type int or string and check for specific values

 

We also added a new variable $EngineArgs (string[]) which contains the arguments passed to the executable.

For example, if you pass the following arguments to the packaged executable:

  packaged.exe –Param1 value1 –Param2 "value 2" –Param3 1

The $EngineArgs variable will contain:

-Param1
value1
-Param2
value 2
-Param3
1

You can use the $EngineArgs variable if you wish to process the packager arguments manually. The $EngineArgs variable makes for a better alternative than using the $Commandline variable, which you would have to parse from scratch.

In an upcoming article we will cover using parameters in packaged executables in more detail.

 

Please continue providing your feedback. Many of the new features included in the service builds are suggestions from users like you. Therefore if you have any suggestions or feature requests, please share them with us on our Wish List and Feature Requests forum.

 

UPDATE: v4.2.97 Corrects a coloring issue with the designer.

 

 
[Google+]   [Facebook]   [LinkedIn]   [StumbleUpon]   [Digg]   [Reddit]   [Google Bookmark]  

Viewing all 308 articles
Browse latest View live