Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all 3333 articles
Browse latest View live

Weekend Scripter: Create Objects from Strings—The Video

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about using Windows PowerShell 5.0 to create objects from strings in this video.

Microsoft Scripting Guy, Ed Wilson, is here. One of the great things about Windows PowerShell is that it is object-oriented. This means that I can easily pipe objects, sort objects, and compare objects.

In Windows PowerShell 5.0, this becomes even easier, because I can create objects from strings. Today I present a video to illustrate this technique:

(Please visit the site to view this video)

Here is a link to the video from YouTube if you would like to download it or play it offline in a different video player: PowerShell 5.0 ConvertFromString demo by Ed Wilson.

Note  For more information, refer to Use New PowerShell 5 Cmdlet to Create Objects from Strings.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy


PowerTip: Use PowerShell to Find Current Connection Profile

$
0
0

Summary: Use Windows PowerShell to find your current connection profile.

Hey, Scripting Guy! Question How can I use Windows PowerShell to see what connection profile my computer is using?

Hey, Scripting Guy! Answer Use the Get-NetConnectionProfile cmdlet.

Weekend Scripter: Parse NetStat with PowerShell 5—The Video

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, shares a video he made that illustrates parsing NetStat with Windows PowerShell 5.0.

Microsoft Scripting Guy, Ed Wilson, is here. For someone who loves working at the command line, the new ConvertFrom-String cmdlet is awesome. I mean, I can do things in a single line of code that in the past, took 15 or 20 lines of code. This means less scripting and more production work.

Today, I am presenting a video to illustrate parsing the output of the NetStat command via Windows PowerShell, but this is simply the surface of how powerful this technique is.

(Please visit the site to view this video)

Here is a link to the video from YouTube if you would like to download it or play it offline in a different video player: Parse NetStat info with PowerShell 5 by Ed Wilson).

Note  For more information about the technique of converting output from NetStat into an object and parsing it with Windows PowerShell, see Parsing NetStat Information with PowerShell 5.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Find Network Adapters that Are Up

$
0
0

Summary: Find your network adapters that are available.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find which network adapters on my computer are up?

Hey, Scripting Guy! Answer Use the Get-NetAdapter cmdlet and filter on the status, for example:

(Get-NetAdapter).where{$_.status -eq 'up'}

Note  This command works on Windows 8.1 and later.

Verify PowerShell Module Manifests

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about verifying Windows PowerShell module manifests.

Microsoft Scripting Guy, Ed Wilson, is here. One of the things that is cool about Windows PowerShell is that it is self-describing. I can type Get-Member or Get-Command and find out what a Windows PowerShell cmdlet is all about. Then there is Get-Help, which also provides way cool information. When cmdlets ship in Windows PowerShell modules, there are additional tools available. I can use Get-Module to see what a module contains.

But there is more…

I can look at the module manifest. When I create a Windows PowerShell module, I always like to create a module manifest. This is more important than it was, say, back in the Windows PowerShell 2.0 days. In fact, if I want to share my module with others, it is essential that I provide a manifest.

About module manifests

Windows PowerShell module manifests are files that have a .psd1 file extension. They are simple text files. Here is an example of a module manifest from the PowerShellGet module:

Image of command output

To find the path to a module, I can use the Path property from the PSModuleInfo object, which is returned by the Get-Module cmdlet, for example:

PS C:\Users\mredw> (Get-Module PSReadline).path

C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.1\PSReadLine.psm1

Note that sometimes this points to the module, and other times, it points to the module manifest. Here is an example of one that points to a module manifest:

PS C:\Users\mredw> (Get-Module Microsoft.PowerShell.Utility).path

C:\windows\system32\windowspowershell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1

Test the manifest

If my path command points to a .psd1 file, I can directly use the Path property to test the module manifest. This is shown here:

Image of command output

There is a lot of information returned by the Test-ModuleManifest cmdlet. The important thing is that in Windows PowerShell 5.0, it also verifies the paths to all associated files. In this way, the Test-ModuleManifest cmdlet is also a troubleshooting tool.

I can use the ModuleBase property to find the location of a module, and therefore, to find the module manifest. This is shown here:

PS C:\> gci (Get-Module PSReadline).modulebase -Filter *.psd1

    Directory: C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.1

Mode            LastWriteTime         Length    Name

----                     -------------                ------        ----

-a----        7/10/2015   7:02 AM            787 PSReadline.psd1

I can then pipe the output to the Test-ModuleManifest cmdlet and examine the manifest:

PS C:\> gci (Get-Module PSReadline).modulebase -Filter *.psd1 | % {Test-ModuleManifest -Path $_.fullname}

ModuleType    Version    Name          ExportedCommands

----------              -------           ----                   ----------

Script     1.1        PSReadline             {Get-PSReadlineKeyHandl...

That is all there is to examining module manifests. Join me tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Find Path to PowerShell Module

$
0
0

Summary: Easily find the path to a Windows PowerShell module.

Hey, Scripting Guy! Question How can I easily find the location where a Windows PowerShell module is installed?

Hey, Scripting Guy! Answer Use the Path property from the PSModuleInfo object that returns from the Get-Module cmdlet, for example:

(Get-Module Microsoft.PowerShell.Utility).path

Add Default Values for PowerShell Module Manifest

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about adding default values to your Windows PowerShell module manifest.

Hey, Scripting Guy! Question Hey, Scripting Guy! I kind of like the idea of creating a manifest for my Windows PowerShell module, but it seems like a lot of busy work. I mean, I seem to always be typing the same thing over and over. I wish there was an easy way to set default values for the module manifest. I thought about taking a blank module manifest, adding default values, and then manually editing the manifest when I needed to customize it… but that seems like a lot of work. Is there an easier way to do this?

—MT

Hey, Scripting Guy! Answer Hello MT,

Microsoft Scripting Guy, Ed Wilson, is here. One of the great things about Windows PowerShell is that it makes it easier to do your work. In fact, that is the entire point. It is not about learning esoteric syntax or memorizing arcane commands—it is about reducing the amount of work you have to do. And that is something I love.

MT, Windows PowerShell makes it easy to specify default values for commonly used cmdlets. This is done via the default parameter values automatic variable: $PSDefaultParameterValues. 

The $PSDefaultParameterValues automatic variable accepts a hash table of values. I wrote about this earlier this year in PowerShell Tips and Tricks: Using Default Parameter Values. I can do a straight-forward parameter assignment, I can use wildcard characters for all parameter with the same name, or I can add a script block that will compute the appropriate value.

The first thing I need to do is look at the syntax of the New-ModuleManifest cmdlet so I can see what parameters are available. To do this, I can use the Get-Command cmdlet and specify the –Syntax switch. This command and the associated output is shown here:

PS C:\> Get-Command New-ModuleManifest -Syntax

New-ModuleManifest [-Path] <string> [-NestedModules <Object[]>] [-Guid <guid>] [-Author

<string>] [-CompanyName <string>] [-Copyright <string>] [-RootModule <string>]

[-ModuleVersion <version>] [-Description <string>] [-ProcessorArchitecture

<ProcessorArchitecture>] [-PowerShellVersion <version>] [-ClrVersion <version>]

[-DotNetFrameworkVersion <version>] [-PowerShellHostName <string>]

[-PowerShellHostVersion <version>] [-RequiredModules <Object[]>] [-TypesToProcess

<string[]>] [-FormatsToProcess <string[]>] [-ScriptsToProcess <string[]>]

[-RequiredAssemblies <string[]>] [-FileList <string[]>] [-ModuleList <Object[]>]

[-FunctionsToExport <string[]>] [-AliasesToExport <string[]>] [-VariablesToExport

<string[]>] [-CmdletsToExport <string[]>] [-DscResourcesToExport <string[]>]

[-PrivateData <Object>] [-Tags <string[]>] [-ProjectUri <uri>] [-LicenseUri <uri>]

[-IconUri <uri>] [-ReleaseNotes <string>] [-HelpInfoUri <string>] [-PassThru]

[-DefaultCommandPrefix <string>] [-WhatIf] [-Confirm] [<CommonParameters>]

Now, I pick the parameters I want to set default values for. The following looks like what I want to assign:

Author, CompanyName, Copyright, FunctionsToExport, aliasesToExport, and VariablesToExport.

To do this, I basically need to paste my assignment line several times, so I end up with the following:

Image of command output

Now, it is simply a matter of type and assign. When I am finished, my code looks like this:

$PSDefaultParameterValues = @{

    "New-ModuleManifest:Author" = "Ed Wilson" ;

    "New-ModuleManifest:CompanyName" = "Microsoft" ;

    "New-ModuleManifest:Copyright" = "2015" ;

    "New-ModuleManifest:FunctionsToExport" = "*" ;

    "New-ModuleManifest:AliasesToExport" = "*" ;

    "New-ModuleManifest:VariablesToExport" = "*" ;

}

I can now create a new module manifest by simply passing the path for the module:

New-ModuleManifest -Path "C:\fso\mymodule.psd1"

The following shows the output after I created my default parameter values my new module:

Image of command output

As you can see here, I can view my module manifest in Notepad:

Image of command output

If I like the results, I can add the code to my Windows PowerShell profile, so that every time I open Windows PowerShell, it will create the default values.

MT, that is all there is to using custom default Windows PowerShell parameter values. Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find Custom Default PowerShell Parameter Values

$
0
0

Summary: Learn how to find custom default Windows PowerShell parameter values.

Hey, Scripting Guy! Question How can I find what custom default Windows PowerShell parameter values I have set up on my
           Windows PowerShell console?

Hey, Scripting Guy! Answer Check the value of the $PSDefaultParameterValues variable, for example:

PS C:\> $PSDefaultParameterValues


New PowerShell 5 Feature: Enumerations

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about creating enumerations in Windows PowerShell 5.0.

Microsoft Scripting Guy, Ed Wilson, is here. It is nearly a stealth feature in Windows PowerShell 5.0—there is an Enum keyword. Yep, that's right, there is an Enum keyword. I wonder what it does? Probably has something to do with creating enums.

Is this a big deal? You betcha...as they may say in some places.

Why? Because prior to Windows PowerShell 5.0, you had to basically create an enum by using C# kinds of code, and then adding it as a type. Did it work? Sure it did. Was it Windows PowerShell? Well, in that it actually worked and I wrote it in Windows PowerShell—sure it was Windows PowerShell.

Note  For reference, refer to my Hey, Scripting Guy! Blog post The Fruity Bouquet of Windows PowerShell Enumerations.

Before PowerShell 5.0

Before Windows PowerShell 5.0, if I wanted to create an enumeration, I basically wrote inline C# code. Here is an example that creates a simple enumeration that assigns numeric values to three different types of fruit:

# Create-FruitEnum.ps1

$enum = "

namespace myspace

{

public enum fruit

{

apple = 29, pear = 30, kiwi = 31

}

}

"

Add-Type -TypeDefinition $enum -Language CSharpVersion3

This is pretty cool code, and the fact that I could create a custom enum in a scripting language was pretty wild. I wrote this code in 2010, and it has worked ever since. In fact, nothing has improved in this regards in the past five years–—until Windows PowerShell 5.0 came out in Windows 10.

Use the enum keyword

So, whereas I used to have to create a giant string, with embedded C# code, and then use the Add-Type command to add in C# code, now I have an enum keyword. This makes the code much cleaner, and very easy to use.

I use the enum keyword and assign a name for the enum. I then open and close a script block. This appears here:

Enum Fruit

{

}

Now I simply assign numeric values for each property:

Enum Fruit

{

 Apple = 29

 Pear = 30

 Kiwi = 31

}

When I run my script, it creates the enum. I can then access each property as a static property. This is shown here:

PS C:\Users\mredw> [fruit]::Apple

Apple

The cool thing is that IntelliSense pops up and shows the permissible members:

That is all there is to using enumerations in Windows PowerShell 5.0.  Join me tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: See Enumeration Value in PowerShell

$
0
0

Summary: Learn how to retrieve an enumeration value in Windows PowerShell.

Hey, Scripting Guy! Question How can I see enumeration allowed values in Windows PowerShell?

Hey, Scripting Guy! AnswerPlace the enumeration name in square brackets, and use the double colon syntax to retrieve a specific property.
          IntelliSense will show you permissible values. Here is an example using an enumeration called Fruit:

[fruit]::pear

Working with Enums in PowerShell 5

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about working with enums in Windows PowerShell 5.0 in Windows 10.

Microsoft Scripting Guy, Ed Wilson, is here. Yesterday, I talked about the new stealth feature in Windows PowerShell 5.0 in Windows 10 that permits me to easily create an enum. Enums are great because they provide a concise way for me to check parameters, a great way to make code easier to read, and many other things.

Note  Today's post continues New PowerShell 5 Feature: Enumerations. You should read it prior to reading today's post.

Awhile back, I wrote a function called Get-EnumValues, which has since come to reside in my Windows PowerShell profile. I talk about this function in One of My Favorite PowerShell Functions. What is cool about the function is that it accepts an enum, and then it returns an array of the enumeration names and the associated numeric values.

This is an extremely powerful and helpful tool to have around when one is working with enums (whether self-created or one of the thousands of enums that reside in the .NET Framework). 

Here is the function:

Function get-enumValues

{

 # get-enumValues -enum "System.Diagnostics.Eventing.Reader.StandardEventLevel"

Param([string]$enum)

$enumValues = @{}

[enum]::getvalues([type]$enum) |

ForEach-Object { 

$enumValues.add($_, $_.value__)

}

$enumValues

}

To use the function, I simply call Get-EnumValues and specify the name of the enum in quotation marks:

PS C:\Users\mredw> get-enumValues -enum "fruit"

Name                     Value                                                   

----                           -----                                                   

Kiwi                           31                                                      

Pear                         30                                                       

Apple                        29    

One of the cool things I can use is the [enum] type accelerator, and I can use that to display the values that are defined inside an enum. This is shown here:

PS C:\Users\mredw> [enum]::GetValues([type]"fruit")

Apple

Pear

Kiwi

But it does not do what I would expect. I would expect to see the numeric values, not the enumeration names or properties. As shown here, when I reference a property via the enumeration, it simply displays the name again:

PS C:\Users\mredw> [fruit]::Apple

Apple

The secret is knowing that there is a value__ property associated with each enumeration. When I call that, then I get the numeric value:

PS C:\Users\mredw> [fruit]::Apple.value__

29

That is the “trick” that my Get-EnumValues function uses to create the hash table it displays.

Create new enum based on existing enum

One of the really cool things I can do with enums is use them to create new enums. To continue my example from yesterday, I can create more fruit. My original enum is shown here:

Enum Fruit

{

 Apple = 29

 Pear = 30

 Kiwi = 31

}

Now I decide that I want to create more fruit. So I call my new enum MoreFruit:

Enum MoreFruit

{

}

To combine a pear and an apple, I get a Papple. It is as simple as calling the pear enumeration and the apple enumeration and adding them together. This is shown here:

Papple = [fruit]::Pear + [fruit]::Apple

I can also combine a kiwi and an apple and get a Kapple:

Kapple = [fruit]::Kiwi + [fruit]::Apple

I imagine that I could combine a kiwi, a pear, and an apple and get a KaPapple, and this is what I do:

KaPapple = [fruit]::Kiwi + [fruit]::Pear + [fruit]::Apple

The complete script is shown here:

Enum Fruit

{

 Apple = 29

 Pear = 30

 Kiwi = 31

}

Enum MoreFruit

{

 Papple = [fruit]::Pear + [fruit]::Apple

 Kapple = [fruit]::Kiwi + [fruit]::Apple

 KaPapple = [fruit]::Kiwi + [fruit]::Pear + [fruit]::Apple

}

When I run it, I can access the KaPapple from my MoreFruit enum:

PS C:\Users\mredw> [morefruit]::KaPapple

KaPapple

I can also see the numeric value of the KaPapple:

PS C:\Users\mredw> [morefruit]::KaPapple.value__

90

I see that it added 29, 30, and 31 together to get 90. I can now use my Get-EnumValues function to see what else is in my MoreFruit enum. The output is shown here:

Image of command output

That is all there is to using enums. Join me tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find Numeric Value of Enum in PowerShell

$
0
0

Summary: Learn how to easily find the numeric value of an enum in Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily find the numeric value of an enumeration?

Hey, Scripting Guy! Answer Use square brackets to call the enum, call the enumeration property as a static property, and reference3
           the value__ property. Here is an example using the [fruit] enum created in yesterday’s post, 
           New PowerShell 5 Feature: Enumerations:

[fruit]::apple.value__

August 2015 PowerShell Spotlight

$
0
0

Summary: Microsoft PowerShell MVP, Teresa Wilson, talks about community activities.

Microsoft Scripting Guy, Ed Wilson, is here. In case you haven’t noticed, I have been turning the keyboard over to Teresa (PowerShell MVP, and my real life wife, aka the Scripting Wife) once a month so she can spotlight community happenings. Today is the day for her August post. Take it away Teresa...

Greetings everyone.

I hope you have had a scriptastic month. I have been looking at the calendar and checking the RAM in my head to share upcoming events with you.

The first item is the Nashville PowerShell User Group meeting. The normal date is the second Tuesday of the month. However, in October, Ed and I will be in Nashville for other business, and they are going to hold a special meeting on Wednesday, October 28. There are no details posted online yet, but you can save the date if you like.

Next I would like to talk a little about the PowerShell Cruise coming up in June 2016. I am so excited about this event—it looks really great, but we will not be attending. I can’t state loud enough or long enough that Ed and I are in full support of this event and would love to attend, but I am so scared of the ocean that I simply cannot get on a cruise ship. So please don’t think we are not in support of this event because we are not there. I suggested looking at having a similar event on a train. So maybe one of these days, that can be looked into for a PowerShell event.  

Last, but not least this month, let me mention the 2016 PowerShell Summit NA, which will be April 4-6, 2016 in Redmond, WA. The call for topics is currently open through October 1, 2015. Please go to this link on Richard Siddaway's Blog for instructions about submitting a topic: PowerShell Summit NA 2016 – Call for Topics.

That is all for now. Don’t forget to attend and support your local user groups. If you do not have one, there is the Virtual User group, and a few of the in-person groups have broadcasting abilities. Let me know if you need any help identifying a group.

Join Ed tomorrow when he will present a video recap about Windows PowerShell module manifests.

~Teresa

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: See Number of Errors in PowerShell Session

$
0
0

Summary: Learn how to determine how many errors there are in the Windows PowerShell session.

Hey, Scripting Guy! Question How can I determine how many current errors there are in my Windows PowerShell session?

Hey, Scripting Guy! Answer Use the Count property from the Error object array:

$error.count

Weekend Scripter: PowerShell Module Manifests—The Video

$
0
0

Summary: Ed Wilson presents a recap video where he talks about Windows PowerShell module manifests.

Microsoft Scripting Guy, Ed Wilson, is here. It has been stormy for the last couple of days. It makes for a great time to spend offline playing around with my Windows 10 laptop or Surface Pro 3. Watching the power of the storms is great fun, especially if I am not directly in the path. The way the storm parades across the flat Florida plain makes it really easy to watch it approach. It is like watching a giant storm switch that is flipped from off to on, and then back again.

Anyway, I decided to make a video recap of the articles I wrote earlier in the week about Windows PowerShell module manifests.

Note  For more information, refer to Verify PowerShell Module Manifests and Add Default Values for PowerShell Module Manifest.

(Please visit the site to view this video)

Here is a link to the video from YouTube if you would like to download it or play it offline in a different video player: Module manifest video by Ed Wilson.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Find Specific Help Articles with PowerShell

$
0
0

Summary: Learn how to easily find specific Help articles with Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find a Help article about automatic variables, if I am not sure of the title?

Hey, Scripting Guy! Answer Use the Get-Help cmdlet and begin with about_ , then press Tab expansion. It will cycle through matches.
           If you think the article is about_automatic_Variables, you can begin with the following command:

Help about_a<tab>

To quickly find the specific article, when the title appears, press ENTER to retrieve the article.

Weekend Scripter: PowerShell 5 Enums—The Video

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, presents a video where he recaps his blog posts about Windows PowerShell 5.0 enums.

Microsoft Scripting Guy, Ed Wilson, is here. Today I decided to make a video to summarize my technique for working with enums in Windows PowerShell 5.0 in Windows 10.

Note For more information, refer to New PowerShell 5 Feature: Enumerations and Working with Enums in PowerShell 5.

(Please visit the site to view this video)

Here is a link to the video from YouTube if you would like to download it or play it offline in a different video player: Windows PowerShell Enums by Ed Wilson.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Retrieve Last Token with PowerShell

$
0
0

Summary: Learn how to use Windows PowerShell to retrieve the last token and avoid retyping.

Hey, Scripting Guy! Question I used Get-Process to view a process I launched, and later I wanted to stop the process. How can I do this without
           doing a lot of typing or creating new variables?

Hey, Scripting Guy! Answer The $$ automatic variable contains the last token submitted, so do the following:

PS C:\> notepad

PS C:\> gps $$

Handles  NPM(K)    PM(K)    WS(K) VM(M)   CPU(s)   Id ProcessName

-------     ------    -----      -----   -----   ------        --         -----------

    116       9     1728       7396 ...67     0.06     4668             notepad

At this point, Notepad is still the last token, so you can view it directly, and use it to stop the process:

PS C:\> $$

notepad

PS C:\> Stop-Process -Name $$

Introduction to PowerShell 5 Classes

$
0
0

Summary: Ed Wilson, Microsoft Scripting Guy, talks about Windows PowerShell 5 classes in Windows 10.

Microsoft Scripting Guy, Ed Wilson, is here. It is an interesting morning. We are up early, looking around, and trying to decide if the latest tropical storm is going to become a hurricane...and if it is going to hit or miss Florida.

Of course, in Central Florida, we will get a miss, but still it could mean several days of high winds, lots of rain, a bit of flooding, and perhaps some power outages. So we need to stock up on food and water, and fill up the vehicles with petrol. I am thinking we need to make sure we have lots of tea, scones, and maybe a box or two of biscotti. Throw in some fresh fruit, and I will be set for a week.

I will also make sure I have my extra batteries for my laptop charged up. I have a couple big UPSs, and a cell phone microcell, so maybe all will be good—as long as the Internet provider can keep its end of the pipe up and running.

Certainly, there is enough new stuff in Windows PowerShell 5.0 to keep me entertained for a week—or much longer if need be.

About Classes

One of the cool things about Windows PowerShell 5.0 is that it adds the ability to create a classes. So, what is cool about that? That might be hard to say really. For example, it might be important to know what a class is, where a class might be used, and so on.

In object-oriented programming, we use objects. That makes sense, I guess. Everything is an object, and objects can contain other objects, and so on. But where do these objects come from?

Well, they come from classes, and classes are the templates used to create an instance of a class.

Note  Classes are not objects, and objects are not classes. An object is an instance of a class.

A class may have static properties, or even static methods. These are hard-coded into the class, so I do not have to create an instance of the class to gain access to the static method. Instead, it always exists.

One of the really cool things in Windows PowerShell is that these static members (methods or properties) are designated by the double colon, so it is obvious if it is a static member. In the following example, I use the static Now property from the System.DateTime class, and it returns the current date and time:

PS C:\> [datetime]::Now

Friday, August 28, 2015 10:55:32 AM

To create a new instance of a DateTime class, I use one of the constructors that are available. When I have created a new instance of a DateTime class, I have a new DateTime object.

Note  Constructors are often required to create a new object from a class.

What are classes for

Classes can be thought of as containers for methods, properties, enums, and other things. A class becomes a template for an object. For example, suppose we want to create a template for a car. We need to describe the properties of the car:

VIN

Make (Enum)

Model

Color (Enum)

Year

Number of wheels::Static

Number of doors

Type of top

It also has a number of methods, such as:

DriveDownTheRoad::Static

StopAtAStopSign

PlayMusic

SetCruiseControl

Park::Static

There may be events associated with the class. For example, in our car class there may be the following events:

RunOutOfGass

FailureToStart

RunARedLight

GoToFast

It also makes sense that we would create a few enums for our class. For example, color would be a great enum, because in general, cars only come in certain colors. Also type of top might be a good enum because there are convertibles and hardtops (and in the old days, vinyl tops, moon roofs, and T-tops). We might even define an enum for make of car because there are only so many different carmakers. So our enums might look like the following:

Color

TopType

Make

We might also define a few static properties on our car class. All cars have four wheels, and so number of wheels might make a good static property:

NumberWheels

We could have a few static methods also. All cars should implement the DriveDownTheRoad method, and the Park method. So our static methods are:

DriveDownTheRoad

Park

This is exactly the process used for creating a class in Windows PowerShell. The first thing I do is design my class. I need to think about what describes it, what it does, and what its limitations are. After I have spent a decent amount of time designing my class, I begin to write the code—but usually not until I have taken some time to mull over what it is I am trying to do and how I will use the class in the future.

There is an introduction to using classes. Windows PowerShell Classes Week will continue tomorrow when I will talk about implementing a class.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Float PowerShell Help

$
0
0

Summary: Learn how to display your Windows PowerShell Help in a new window.

Hey, Scripting Guy! Question How can I keep my Windows PowerShell Help open so I can look at it while I am trying my new code?

Hey, Scripting Guy! Answer Use the ShowWindow parameter. It will open a new window that contains your Help and allow you to move
           it around on your screen. More importantly, it returns your Windows PowerShell console back to you.
           Here is such a command:

Get-Help about_Classes -ShowWindow

Viewing all 3333 articles
Browse latest View live




Latest Images