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

Use DSC to Install Windows PowerShell DSC Resource Kit Bits

$
0
0

Summary: Learn how to use DSC to install Windows PowerShell Desired State Configuration Resource Kit bits.

Microsoft Scripting Guy, Ed Wilson, is here. Fall has definitely arrived here in Charlotte, North Carolina in the southern portion of the United States. The mornings are cool, the evenings are clear and crisp, and the midday sun does not warm things beyond a reasonable amount. People are out and about—people who I did not even know existed in our neighborhood.

It is a friendly time of the year, and it is one of the main reasons we put up with the oppressive heat and humidity of southern summers. The Scripting Wife and I are thinking about heading to the Renaissance Festival over the weekend. I don’t know for sure yet—but it might be fun. We went to one several years ago, but it is probably about time to go again. After all, how often does one get to see jousting tournaments?

Speaking of jousting…

Today’s post is easy. I am going to install the Windows PowerShell Desired State Configuration (DSC) Resource Kit bits on several servers, and I am going to use DSC to do it. This is because I will not need to have access to the additional DSC resource providers that the Resource Kit provides to accomplish the task.

Why? Well, because Windows PowerShell 4.0 includes DSC and over a dozen resource providers by default. Those I need for today's task are already in the box. And as they may say at the Renaissance Festival, “That doth sweetly ringeth upon mine ears.” They might say that if they know how to use Windows PowerShell to help with their configuration needs.

DSC providers to the rescue

I am going to use two standard DSC resource providers: the File provider and the Archive provider. What is cool about this is that I can use the File provider to copy a .zip file to a specific location on my remote servers. I can then use the Archive provider to unzip the files and expand them to a specific location.

In this case, my file is the ResKit.zip file I copied yesterday from the Script Center Repository, and my destination location is the Program Files\Windows PowerShell\Modules folder that is recommended in the Readme file. I begin my DSC configuration script on my client workstation with the following:

#Requires -version 4.0

Configuration ReskitUnzip

{

 Param ($modulePath = ($env:PSModulePath -split ';' |

    ?  {$_ -match 'Program Files'}),

    $Server = @('S1','S2','DC1'))

Obviously, it requires Windows PowerShell 4.0, so there is no reason not to add this #Requires command to my script. I use the Configuration keyword and specify a name for my configuration. I am calling it ResKitUnzip for obvious reasons. I now specify parameters, like I would in a regular Windows PowerShell function. I find my path for the module folder by splitting the PSModulePath environmental variable and looking for a match with Program Files. When I have that, I assign an array of server names to the $server variable. Cool.

Using providers to do things

Now I need to specify which node I want to do things to. This is easy. I will assign my array of server names to the node parameter. I then use the File provider to specify that I want to copy my source files from my DC1 share location.

The destination path will become a location on each local server, and it does not need to exist prior to this operation. This is, in fact, what the Ensure command does—it makes certain the folder exists, and then it will copy all of the files to the location. I use the type of Directory because it will create a directory and copy all of my files there. Here is this portion of the configuration:

node $Server

    {

      File ScriptFiles

      {

        SourcePath = "\\dc1\Share\DSCResKit"

        DestinationPath = "C:\DSCResKit"

        Ensure = "present"

        Type = "Directory"

        Recurse = $true

      }

The Archive provider works the same way. I use the Archive provider keyword and specify a name for the operation. I specify that it depends on the previous operation (which I called ScriptFiles), and I specify my destination. Again, this is the destination that is relative to each of my local servers. I then ensure that it is present. That is it. This automatically extracts the zipped files and places them in the location I specified. Here is this portion of the operation:

      Archive ZippedModule

      {

        DependsOn = "[File]ScriptFiles"

        Path = "C:\DSCResKit\Reskit.zip"

        Destination = $modulePath

        Ensure = "Present"

      }

Now I call the configuration and specify my output for the configuration. This output is created locally to the computer from which I run my configuration script. Here is the command:

ReskitUnZip -output C:\serverConfig

Inside this folder, there are three .mof files that will be used to configure the three remote servers. Here is a view of that folder:

Image of menu

The last thing I do is start the configuration with this command:

Start-DscConfiguration -Path C:\serverConfig -JobName ServerConfig -Verbose

The output tells me how long it takes to do the configuration, in addition to the .mof files that are created and status about them. Here is the output:

Image of command output

The complete configuration script is shown here:

# Script: DSCResKitUnzip.ps1

#Requires -version 4.0

Configuration ReskitUnzip

{

 Param ($modulePath = ($env:PSModulePath -split ';' |

    ?  {$_ -match 'Program Files'}),

    $Server = @('S1','S2','DC1'))

    node $Server

    {

      File ScriptFiles

      {

        SourcePath = "\\dc1\Share\DSCResKit"

        DestinationPath = "C:\DSCResKit"

        Ensure = "present"

        Type = "Directory"

        Recurse = $true

      }

      Archive ZippedModule

      {

        DependsOn = "[File]ScriptFiles"

        Path = "C:\DSCResKit\Reskit.zip"

        Destination = $modulePath

        Ensure = "Present"

      }

    }

}

 

ReskitUnZip -output C:\serverConfig

Start-DscConfiguration -Path C:\serverConfig -JobName ServerConfig -Verbose

That is all there is to using DSC to install Windows PowerShell DSC Resource Kit bits. DSC Resource Kit Week will continue tomorrow when I will talk about more cool providers.

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 See If WinRM Is Running on Remote Computer

$
0
0

SummaryLearn how to easily use Windows PowerShell to check if WinRM is running on a remote computer.

Hey, Scripting Guy! Question How can I use Windows PowerShell to ensure that WinRM is running and configured on my three remote computers?

Hey, Scripting Guy! Answer Create an array of computer names, and pipe them to the Test-WsMan cmdlet, for example:

"s1","s2","dc1" | % { Test-WSMan $_ }

Note  % is an alias for the Foreach-Object cmdlet.

Use PowerShell DSC to Check Pending Reboot

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell and DSC to check a pending reboot.

Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife and I started the week by heading to the Microsoft office to get our flu shots. Luckily, the flu shot did not require a reboot—but that actually got me thinking.

In the old days, I mean, in the really old days, it was fairly easy to check for a pending reboot. I simply read a key from the registry, and that was (as they say) that. But things have gotten more complicated. In fact, Microsoft PFE, Brian Wilhite, wrote a pretty popular script that detects pending reboot. (You can find this script on the Script Center Repository: Get-PendingReboot—Query Computers for Pending Reboot State.)

I believe at the heart of it, he checks four different things. Brian's script is cool—but dude, it is a lot of lines of code. I prefer Windows PowerShell and DSC.

Using the DSC Resource Kit xPendingReboot resource

One of the new DSC resources from the DSC Resource Kit is the xPendingReboot resource. It permits me to check if a reboot is required, and if it is, to perform that reboot.

There are a few prerequisites. There is a Windows update for Windows 8.1 and Windows Server 2012 R2 that is required for the Import-DSCResource command to work. To download this update, see article 2883200 in the Microsoft Knowledge Base. This update comes via Windows Update automatically, so if your machine is up-to-date on updates, it is already there. If not, ensure that you have the update.

After this one, there is another update. See article 289872 in the Microsoft Knowledge Base. After you have the updates and reboot, you will not be able to use Import-DSCResource directly. You can only use it inside the Windows PowerShell ISE and when you are writing a DSC. It looks like a cmdlet, but it is not. Tab expansion does not work for this command either, and it does not accept positional parameters. Therefore, the following command generates an error message:

Import-DSCResource xPendingReboot

The error message is rather complete, as shown here:

Keep in mind, however, that if I use the following command, I still get an error message. First, the Windows PowerShell ISE takes a long time to error out. Then it comes back and says it cannot find the resource because a quick check of the folder and all of the files reveals that everything should be in good shape. This one is not so easy to figure out:

Image of command output

Why can’t it find the resource? Why can’t it load the resource? Well, because I need to specify –module, and not –name. When I do that, everything works like clockwork. Here is the command:

Import-DscResource -module xPendingReboot

     Note  Remember that with each of the xfiles (DSC resources from the DSC Resource Kit), I need to explicitly use
     Import-DSCResource to import the DSC resource. Also keep in mind that although the command Import-DSCResource
     appears to be a cmdlet, it is not. It does not support Tab expansion, it does not take positional parameters, and you
     cannot use Get-Help Import-DSCResource.

So how do I use this resource provider? It is simple. I create a new configuration and provide it with a name. I also specify my node name (but I can use this on multiple nodes). Here is that portion of the configuration:

Configuration CheckForPendingReboot

{       

  Import-DscResource -module xPendingReboot

    Node ‘edlt’

    {  

Now I call the provider, and I specify the name:

xPendingReboot Reboot1

        {

            Name = ‘BeforeSoftwareInstall’

        }

I call the LocalConfigurationManager, and I specify to reboot if a reboot is needed:

LocalConfigurationManager

        {

            RebootNodeIfNeeded = 'True'

        } 

 Now I create my .mof file from the configuration, and I start the configuration:

CheckForPendingReboot -OutputPath c:\edlt\PendingReboot

Start-DscConfiguration -path c:\edlt\PendingReboot -wait -Verbose

Here is the complete script:

Configuration CheckForPendingReboot

{       

  Import-DscResource -module xPendingReboot

    Node ‘edlt’

    { 

        xPendingReboot Reboot1

        {

            Name = ‘BeforeSoftwareInstall’

        }

        LocalConfigurationManager

        {

            RebootNodeIfNeeded = 'True'

        }

    } 

}

 

CheckForPendingReboot -OutputPath c:\edlt\PendingReboot

Start-DscConfiguration -path c:\edlt\PendingReboot -wait -Verbose

When I specify the configuration with the –Verbose cmdlet, I get a nice output that tells me about each step of the configuration and how long the activities take. Here is the script and the output:

Image of command output

That is all there is to using Windows PowerShell to check a pending reboot. DSC Resource Kit Week will continue 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: Check Status of PowerShell Help Files on Remote Computers

$
0
0

Summary: Use Windows PowerShell to check the status of Help file updates on remote computers.

Hey, Scripting Guy! Question How can I easily see if the Windows PowerShell Help files are up-to-date on my remote computers?

Hey, Scripting Guy! Answer Use the Invoke-Command cmdlet, target the remote computers, use Get-Help to look for help,
           and then use the Select-String cmdlet to search for “Cannot find the Help files” in the output.
           Here is an example (this is a single-line command broken at the pipeline character for readability):

Invoke-Command -CN "s1","s2","dc1" -ScriptBlock { get-help help |
Select-String "cannot find the Help files" -Quiet}

Use PowerShell and DSC to Enable Logging

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell and the Desired State Configuration Resource Kit to enable logging.

Microsoft Scripting Guy, Ed Wilson, is here. Dude, a pumpkin patch sprung up across the street from us. On my walk to the university, I passed at least three pumpkin patches. I guess that means there was a bumper crop of pumpkins this year. I'm not sure why one would need so many of the large orange squashes. I mean, you can make soup, or a pie, or even roast the seeds. Beyond that, I am at a loss. Oh well...

There are some things that do fill an obvious need, however—such as the xWinEventLog provider from the Desired State Configuration (DSC) Resource Kit. What does it do? It permits me to easily turn or turn off logging for a particular log on a remote server. It also lets me specify the logging mode and set the maximum log size. Groovy.

Although I can do this manually, it is not always the most efficient thing to do. For example, if I want to use the Event Viewer to connect to a remote server to turn on, turn off, or view event logs, I need to poke holes in my firewall. Which ones? Dude, at this point I am not even sure.

I might also need to turn on a service. I wrote a script a long time ago that enabled these sorts of remote management utilities, and I had to poke several holes in the firewall and start several services to do so. It took a lot of research to figure out what exactly was needed. I spent over a week writing that script.

But by using DSC, I can do this quickly. Here is what happens, by default, when I try to connect to a remote event log:

Image of error message

Not only do I get an error message, but it also wastes a lot of time. I can pretty much write my DSC configuration and run it in the amount of time it takes to launch Event Viewer, retarget to a remote server, and wait for the error message.

When I find the log, maybe by going to the remote server, I can right-click the name of the log and examine the properties. Here is what I find:

Image of menu

Write the DSC configuration script

How hard is it to write a DSC configuration script? Well, it is pretty simple. I make sure I have the DSC resource by using Get-DSCResource. (I obtained the provider from the Script Center Repository: DSC Resource Kit.) You can download the providers one at a time, but I prefer to get them all at once.

The first thing I do is use the Configuration keyword and set the name for my configuration. I then specify the servers upon which I want to enable logging. I import the xWinEventLog DSC provider, and specify the full name of the log I want to enable. Here is that bit of code:

configuration EnableWMILog

{

    $Server = @('s1','s2')

    Import-DscResource -module xWinEventLog

    $logname = "Microsoft-Windows-WMI-Activity/Operational"

    node $Server

Next, I call the xWinEventLog provider and specify the log name, if I want to enable or disable the log, the logging mode, and the size of the log. Here is that portion of the DSC configuration script:

xWinEventLog WMILog

        {

            LogName            = $logname

            IsEnabled          = $true

            LogMode            = "AutoBackup"

            MaximumSizeInBytes = 2mb

        }

    }

Now I call the configuration and specify an output path for the MOF files that are created:

EnableWMILog -OutputPath c:\DSC\WMILog 

The last thing I do is start the DSC configuration of the remote servers. I use the –Verbose parameter to provide information such as verbose logging (which lets me know what is going on) and how long the configuration takes. I do not need to specify the server names again, because when I call the configuration script, it creates a MOF file for each server. When I specify the path for Start-DSCConfiguration, it reads all the MOF files and applies the configuration. Here is the script:

Start-DscConfiguration -Path C:\DSC\WMILog -Verbose -wait -debug

Here is the complete configuration script. It is 19 lines long, including blank lines, braces, and such.

configuration EnableWMILog

{

    $Server = @('s1','s2')

    Import-DscResource -module xWinEventLog

    $logname = "Microsoft-Windows-WMI-Activity/Operational"

    node $Server

    {

        xWinEventLog WMILog

        {

            LogName            = $logname

            IsEnabled          = $true

            LogMode            = "AutoBackup"

            MaximumSizeInBytes = 2mb

        }

    }

}

EnableWMILog -OutputPath c:\DSC\WMILog

Start-DscConfiguration -Path C:\DSC\WMILog -Verbose -wait -debug

Now whenever I run WMI scripts on the remote servers, I will have diagnostic logging. When things are working properly again, I can modify my DSC configuration and easily turn off the logging. Piece of cake—pumpkin or otherwise.

That is all there is to using DSC. DSC Resource Kit Week will continue tomorrow when I will talk about more way 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: Use PowerShell to Remove Characters in a String

$
0
0

Summary: Learn how to use Windows PowerShell to remove specific characters in a string.

Hey, Scripting Guy! Question I have a string that includes braces:

$a = '{Abcde}'

   I want to remove the braces, but keep the text string inside the braces.
   How can I do this by using Windows PowerShell?

Hey, Scripting Guy! Answer Use the –Replace operator, create a regular expression pattern that includes only the braces you want to remove,
           and then write the results back to the variable, for example:

PS C:\> $a = '{Abcde}'

PS C:\> $a -replace '[{}]',''

abcde

PS C:\> $a = $a -replace '[{}]',''

PS C:\> $a

abcde

Note  This command uses single, back-to-back quotation marks .

Use PowerShell DSC to Configure Internet Explorer

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Desired State Configuration to configure Internet Explorer on servers.

Microsoft Scripting Guy, Ed Wilson, is here. This morning I decided to use my single-cup tea infuser to make a cup of Orange Cream tea using some leaves I brought back from Germany. I then decided to add a lemon slice to the cup. I should have known better. I won’t say I ruined my cup of tea—OK, I will say that. But I still drank it because I hate to waste a nice cup of tea, and I especially don’t want to waste the leaves that I cannot find here in Charlotte.

Speaking of things I don’t like to, or don’t want to do again…

I personally do not like having a web browser on a server. Of all the potential security risks, this one is a biggie. This is why I love the Enhanced Security Configuration in Internet Explorer. As far as I know, it means that Internet Explorer doesn’t work—at least not very well. I cannot even surf over to TechNet or to the Script Center Repository with this thing turned on. Cool.

Of course (in my humble opinion), the best configuration for servers is Server Core mode, and then use Windows PowerShell to do everything. This is where Windows PowerShell comes to the rescue if I have servers with the GUI still installed.

I can ensure that at least Internet Explorer is running with Enhanced Security Configuration. By default, when I finish installing my Windows Server software (beginning with Windows Server 2008), Enhanced Security Configuration is set for Internet Explorer. This means that if it is turned off, someone (with Administrator rights) has turned it off. I can confirm this by looking in Server Manager. This is shown here:

Image of menu

Create and apply the configuration

The first thing I do is create a configuration. I specify the name, and I import the Desired State Configuration (DSC) Resource Kit. I then specify my servers and the node as shown here:

Configuration EnableIEEsc

{

    Import-DSCResource -Module xSystemSecurity -Name xIEEsc

    $server = @('s1','s2')

    Node $server

    {

Next I use xIEEsc to enable the Enhanced Security Configuration. I want to do this for Administrators and for normal users, so I actually have to specify the call twice. This is shown here:

xIEEsc EnableIEEscAdmin

        {

            IsEnabled = $True

            UserRole  = "Administrators"

        }

        xIEEsc EnableIEEscUser

        {

            IsEnabled = $True

            UserRole  = "Users"

The parameters are pretty self-evident. But if I did not know what the parameters were, or if I was unclear as to what the parameter wanted, I can use IntelliSense. I highlight xIEEsc, and then either press Ctrl + Spacebar, or right-click and choose Start IntelliSense from the action menu. This provides IntelliSense for the options available.

When I am done, I close out the braces, call the configuration, and start DSC. Here is that portion of code:

  }

    }

}

EnableIEEsc -OutputPath c:\dsc\IEESC

Start-DscConfiguration -Path c:\dsc\ieesc -Wait -Verbose

The complete configuration script is shown here:

Configuration EnableIEEsc

{

    Import-DSCResource -Module xSystemSecurity -Name xIEEsc

    $server = @('s1','s2')

    Node $server

    {

        xIEEsc EnableIEEscAdmin

        {

            IsEnabled = $True

            UserRole  = "Administrators"

        }

        xIEEsc EnableIEEscUser

        {

            IsEnabled = $True

            UserRole  = "Users"

        }

    }

}

EnableIEEsc -OutputPath c:\dsc\IEESC

Start-DscConfiguration -Path c:\dsc\ieesc -Wait -Verbose

The script and its associated output are shown here:

Image of command output

I navigate to one of my remote servers to see if it worked. As shown here, it worked fine:

Image of menu

That is all there is to using DSC to configure Internet Explorer Enhanced Security Configuration on servers. This also concludes DSC Resource Kit Week. Join me tomorrow when I will discuss "Why learn Windows PowerShell?"

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: Change the PowerShell Prompt

$
0
0

Summary: Learn how to shorten the Windows PowerShell prompt.

Hey, Scripting Guy! Question I am concerned that the Windows PowerShell prompt is becoming too long when working with the registry or the
           file system, and I would like to shorten it.

Hey, Scripting Guy! Answer Change the prompt with the following one-liner (remember to add a space at the end of the prompt
           for reading ease):

Function prompt {“My Prompt “}

When you close Windows PowerShell, the prompt returns to the original configuration.

Note  Today's PowerTip is supplied by Windows PowerShell MVP, Jeff Wouters.


Weekend Scripter: Why Learn PowerShell?

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about why to learn Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. Every once in a while, I am asked, “Why should I learn Windows PowerShell?”

To be honest, that is always a bit of a troublesome question. Not because I cannot answer it, but because to me the question is nearly irrelevant. I will confess that I love using Windows PowerShell. I use it every day, and when I am not using it, I am actually thinking about it.

Recently, I was getting dressed to head out to the gym, and a Windows PowerShell command popped into my head. I called the Scripting Wife and asked her for a pencil and a piece of paper so I could write the command down before I forgot it. I then scurried out to the gym, and when I returned, I tried the command and it worked perfectly. Cool. I ended up using it as a PowerTip.

So what is the problem with answering the question, "Why learn Windows PowerShell?" Well, it is that I am not certain I ever asked myself this question. I assumed I would learn it as soon as I first heard about it. But then, I guess everyone is not like that. So I decided to look at the issue from two perspectives: "Why not learn Windows PowerShell?" and "Why learn Windows PowerShell?" First of all, let me look at why not learn Windows PowerShell.

Don’t learn Windows PowerShell

Don’t bother learning Windows PowerShell if you already have scripts for everything and you can perform all of your automation needs with those existing scripts. I mean, really. There is absolutely no reason to translate a perfectly working VBScript, Perl script, or T-SQL script into Windows PowerShell if you don’t need to do so.

The purpose of writing a script is to avoid work, and if the process generates more work, then, dude, don’t bother. There are probably a few shops that are in this state. They have highly developed automation systems in place, are not on the cutting edge of technology, and are perfectly happy with what they do, how they do it, and the capabilities it provides. If you find yourself in this situation, don’t bother learning Windows PowerShell. It will not do you any good.

If you are planning on leaving the IT profession in, let’s say, the next six months, then you can probably escape from having to learn Windows PowerShell if you have managed to do so to this point. I am not picking on the senior IT pros who are waiting to retire. I hope that I am talking about the some young person who has decided that rather than learning a new technology every year and staying abreast of current trends in the profession, they would rather chuck it all, move to the Caribbean and open a dive shop. I would much rather teach scuba diving, and spend my days floating around and photographing eels, sharks, giant groupers, and various coral heads, than writing Windows PowerShell script any day of the week. And as I said earlier, I love Windows PowerShell. But compared to scuba diving all day long? Forget it.

You might not want to bother learning Windows PowerShell if your particular piece of technology does not have Windows PowerShell coverage. Of course at this point, I am not sure I could think of what that technology may be. But hey, it might exist. With complete access to the .NET Framework, WMI, ADSI, and the Win32 API, it is pretty hard to image that you might have a technology that Windows PowerShell cannot talk to. But if you do, then it probably is not worth the effort to learn Windows PowerShell.

Learn Windows PowerShell

If you have more than one system to manage, and if that system runs a version of the operation system that was created since about 2003, you really should learn Windows PowerShell. But maybe you used to use VBScript or Perl to manage your systems. Fine—see the above section. But if you find yourself needing to create new scripts, or to do new things to your system, you should begin incorporating Windows PowerShell. This is because VBScript has not been improved since Windows XP came out, and Perl is not even standard in the Windows build environment.

How hard is it to learn Windows PowerShell? Windows PowerShell can be as easy to learn as finding the Windows PowerShell console or the Windows PowerShell ISE, opening it, and typing Get-Process. This one command provides information about all the processes running on your local system. To retrieve them from a remote system, you use Get-Process –ComputerName mycomputer. That is it. It is that simple. Of course, it gets harder. The thing is that after you learn the basics, they transfer to other Windows PowerShell cmdlets and to other technologies.

There are lots of resources to help you learn about Windows PowerShell. One of the best ones (and it is free) is the Hey, Scripting Guy! Blog. Published seven days a week, twice a day, it is the single largest collection of Windows PowerShell information on the Internet. Of course, there are also local user groups, online user groups, Twitter feeds, Facebook groups, and resources via Linked In. In addition, there are hundreds of videos on YouTube related to Windows PowerShell. It is not a problem to find helpful information—the problem is sifting through the plethora of resources. But hey, that is better than not finding anything by a long shot.

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 Errors Related to Update-Help

$
0
0

Summary: Use Windows PowerShell to find errors related to Update-Help.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find if Update-Help is completing successfully on my computer?

Hey, Scripting Guy! Answer Use the Get-WinEvent cmdlet and search Windows PowerShell logs for event 4103 and a status level of 2 (error).
           You can narrow the results by adding a start time. When you find the events, use Select-Object and the 
           –ExpandProperty parameter to expand the message field. Here is a command that looks for errors beginning on
           Sept. 29, 2014 (this is a one-line command that wrapped for readability):

Get-WinEvent -FilterHashtable @{
providername="*powershell*";Level=2;StartTime="9/29/14";ID=4103}

Weekend Scripter: Why upgrade to PowerShell 4.0?

$
0
0

Summary: Microsoft Scripting Guy Ed Wilson talks about why to upgrade to Windows PowerShell 4.0

Microsoft Scripting Guy, Ed Wilson, is here. I am kicking off a week of posts that are written by Windows PowerShell MVPs, a member of the product group, and myself, in which we are going to talk about upgrading to Windows PowerShell 4.0. For each of us, the reasons vary a bit.

Why is this important? The short answer is that Windows PowerShell is a crucial technology from Microsoft, and it is central to our management strategy. With the shift to the cloud, Windows PowerShell takes on an even greater role in management.

Background: Windows PowerShell 1.0

If you are a regular reader of this blog, I imagine you are familiar with the previous paragraph. But for me, the central answer is that I do not want to fall behind. I do not want my skills to get out of date. Think about this: If you began using Windows PowerShell when it first came out, you only had 129 cmdlets to learn. It was basically on par with VBScript.

This was cool because that is where I came from. If I wanted to do anything really cool with Windows PowerShell, I had to use COM, WMI, or ADSI. Like I said, no biggie because that was the VBScript world. It wasn’t simple, but it was a straightforward migration, if you will.

I had to learn about new Windows PowerShell concepts, get my head around the idea that everything is an object, and learn a few new ways of doing things—but that was about it. After using it for a year or so, I had a real good handle on Windows PowerShell...and then came the beta of Windows PowerShell 2.0.

A new ball game: Windows PowerShell 2.0

Windows PowerShell 2.0 nearly doubled the number of cmdlets—up to around 229. It added new features, such as Windows PowerShell Remoting, and powerful and complicated cmdlets like Get-WinEvent.

It introduced things like Advanced Functions, comment-based Help, modules, the Windows PowerShell ISE (with its own object model), and graphical cmdlets such as Out-Gridview. I could go on and on and on. It is absolutely amazing how much the Windows PowerShell team added in such a short time.

But you know what? I did not panic. Why? Because I already knew Windows PowerShell 1.0 very well. I had studied, learned, and pushed the boundaries for Windows PowerShell 1.0 (in addition to when it was in beta). So when Windows PowerShell 2.0 shipped, I was ready for the next great Windows PowerShell. In fact, I was happy to see it because I was running up against real limitations of Windows PowerShell 1.0.

On the other hand, if I had been confronted with Windows PowerShell 2.0 from the outset, with no exposure to Windows PowerShell 1.0, dude, I would have been crying. As an example, my book about Windows PowerShell 1.0 was around 300 pages—and I covered, in detail, all of the major features of Windows PowerShell 1.0 and how to implement them in a Windows world. My book about Windows PowerShell 2.0 was over twice that size—and I had to leave stuff out.

The big Windows PowerShell 3.0

If Windows PowerShell 2.0 was a huge release, then Windows PowerShell 3.0 was a mega release. I feel like I am running out of superlatives. There were so many new features introduced in Windows PowerShell 3.0, that I have not even finished writing about them all—either on the Hey, Scripting Guy! Blog or in book form.

I have written two books about Windows PowerShell 3.0, and I have not covered everything. For example, one way cool feature (sort of a stealth feature) is the Windows PowerShell Web Access. This is something I keep meaning to write about. It is a way cool feature that lets me set up a web server and run Windows PowerShell commands against my servers. Slick.

We added new features to the Windows PowerShell ISE, such as code snippets and improved Tab expansion. We added support for disconnected Windows PowerShell sessions. One of the big features was the CIM cmdlets and subsystem. This feature added literally thousands of cmdlets beginning with Windows PowerShell 3.0 (in Windows 8 and Windows Server 2012).

Note  This feature relies on a subsystem that is not available in Windows PowerShell 7.0 or earlier.

We also added support for updatable Help, scheduled jobs, auto loading of modules. Oh, yeah, if that was not enough, we also added Windows PowerShell Workflows.

Any one of these features could take a year to work through and to get really good at. Taken in total, all I can say is, "DUDE!" I would really hate to begin my learning of Windows PowerShell at the 3.0 level.

Out of the park with Windows PowerShell 4.0

Before I got through working with all the new features in Windows PowerShell 3.0, boom! Out comes Windows PowerShell 4.0. It added Desired State Configuration (DSC). But there were also a lot of other features added.

We vastly improved working with constrained run spaces, and we added the ability to save Help, which is great for updating the Help in sandboxed environments. We added new features to cmdlets, such as Invoke-RestMethod and Invoke-WebRequest. We simplified the syntax of the Where operator, and added new cmdlets, such as Get-FileHash.

The big feature is, of course, DSC. But the numerous features added to the existing cmdlets make discovery an ongoing new process.

And now: Windows PowerShell 5.0

Windows PowerShell 5.0 is currently in community preview. This is your chance to try to get ahead of the curve…or maybe a chance to catch your breath.

Being an IT pro is hard work. We all know this. There are long hours, endless learning, and the constant demand to do more with less. Staffs are cut and jobs are outsourced. Yet the number of unmanaged devices and complexity of networks continue to grow, literally unchecked. Add to this the pressures of regulations and security constraints, and it seems to be an impossible situation. But it is the job we love, and the rewards are great.

Windows PowerShell is one tool that can make a huge difference. The ability to quickly manage hundreds (even thousands) of devices from a single Windows PowerShell script or even a one-line command is not only cool, but it is necessary.

From my perspective the time spent learning Windows PowerShell is one of the quickest ROIs available. Get ahead of the curve and stay ahead of the curve by learning how to leverage the newest features of Windows PowerShell to gain the maximum advantage from this powerful technology.

Stay tuned for this week’s posts as we talk about how to move to Windows PowerShell 4.0. Tomorrow, Windows PowerShell MVP, Richard Siddaway, leads us off with a discussion of the concerns and cautions when planning an upgrade.

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: Get PowerShell Module by Using –FullyQualifiedName Parameter

$
0
0

Summary: Learn how to get a specific Windows PowerShell module by using the –FullyQualifiedName parameter.

Hey, Scripting Guy! Question How can I look at the specific version of a Windows PowerShell module?

Hey, Scripting Guy! Answer In Windows PowerShell 4.0, you can do this by using the–FullyQualifiedName parameter of the 
           Get-Module cmdlet. You specify a hash table that contains the name and version of the module
           (you can also use the GUID). Here is an example using my Windows PowerShell ISE module:

Get-Module –FullyQualifiedName @{modulename="powershellisemodule";moduleversion="4.0"}

Should I Upgrade to Latest Windows PowerShell Version?

$
0
0

Summary: Richard Siddaway discusses the issues around upgrading your version of Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. Today's post is provided by Richard Siddaway...

Richard is based out of the UK and spends his time automating anything, and everything, for Kelway, Ltd. A 7-year Windows PowerShell MVP, Richard is a prolific blogger, mainly about Windows PowerShell, (Richard Siddaway's Blog: A PowerShell MVPs site) and a frequent speaker at user groups and Windows PowerShell conferences. He has written a number of Windows PowerShell books: Windows PowerShell in Practice, Windows PowerShell and WMI, Windows PowerShell in Depth (co-author), Windows PowerShell Dive (co-editor), and Learn Active Directory Management in a Month of Lunches (which features lots of Windows PowerShell). Some new Windows PowerShell books are in the pipeline. All of the books are available from www.manning.com.

Hey, Scripting Guy! Question Hey, Scripting Guy! I’m not using the latest version of Windows PowerShell. Should I upgrade?

—KT

Hey, Scripting Guy! Answer Hello KT,

Richard Siddaway here. That’s a really good question, and it has a short answer and a long answer. The short answer (as with so much in IT) is, “It depends.” The long answer is the rest of this blog post.

IT pros always want the new shiny toys to play with. I’m no exception. But there can be a downside to blindly pushing out an upgrade across all of your servers. Upgrading Windows PowerShell is no exception, and there are a few questions you should be able to answer before performing an upgrade:

  • What benefits am I going to get?
  • What’s the risk—will any of my applications break?
  • Do I actually need the new functionality?
  • Is the machine a client or a server?

Let’s start working our way through these questions. Other questions will come to mind that are specific to your organization and for which you are the only one who can see the issues and find the answers.

I’m assuming that you are looking to upgrade only Windows PowerShell. If you upgrade the underlying operating system, you will automatically upgrade Windows PowerShell, but operating system upgrades are a topic for another time and place.

The first consideration must be about the benefits you are going to get. Most people I speak to are using Windows PowerShell 2.0 or later. I can’t really think of the last time I discussed using Windows PowerShell 1.0. That means your upgrade choices are Windows PowerShell 4.0 or Windows PowerShell 3.0.

You will notice that I have deliberately excluded Windows PowerShell 5.0. At the current time, Windows PowerShell 5.0 is a Community Technology Preview (CTP). It can (and does) change between preview versions. Using a CTP in a production environment is not recommended, and it carries a significant risk that a change will break your code. You have been warned.

Having said that, I’ll explain the currently known benefits of using Windows PowerShell 5.0 so your thinking is future proofed—at least until the next version of Windows PowerShell appears.

Windows PowerShell 3.0 brought a large set of new functionality:

  • Windows PowerShell workflows
  • CIM cmdlets
  • Cmdlets over objects (CDXML)
  • Windows PowerShell Web Access
  • Module automatic loading
  • Updatable Help
  • Robust and disconnected sessions
  • Scheduled jobs

This isn’t the full set of enhancements. For that, read What's New in Windows PowerShell (which also talks about features in Windows PowerShell 5.0 and Windows PowerShell 4.0).

Windows PowerShell 4.0 followed shortly afterwards and brought:

  • Desired State Configuration (DSC)
  • Save-Help
  • Windows PowerShell Web Access improvements
  • Workflow enhancements
  • New features for Windows PowerShell Web Services

Windows PowerShell 5.0, although still under development, has these known new features:

  • Classes can be defined in functionality
  • DSC enhancements
  • OneGet for managing software packages
  • PowerShellGet for managing Windows PowerShell modules through OneGet
  • Transcriptions available in all hosts
  • Major enhancements to debugging, including the ability to debug Windows PowerShell jobs
  • Network switch module
  • Performance gain when using COM objects

After you review the functionality you gain, you need to decide if you actually need the benefits. If you aren’t planning to use DSC, for instance, do you need to upgrade to Windows PowerShell 4.0? Only you can answer that question in the context of your organization.

The next question you have to answer is about risk. Will upgrading Windows PowerShell break any of my applications? Unfortunately the answer is that it might. The Release Notes for Windows PowerShell 4.0 supply the following list of applications with which Windows PowerShell 4.0 is incompatible:

  • System Center 2012 Configuration Manager (not including SP1)
  • System Center Virtual Machine Manager 2008 R2 (including SP1)
  • Microsoft Exchange Server 2013, Microsoft Exchange Server 2010, and Microsoft Exchange Server 2007
  • Microsoft SharePoint 2013 and Microsoft SharePoint 2010
  • Windows Small Business Server 2011 Standard

If your machine is running any of these products, do not install Windows PowerShell 4.0. Windows PowerShell 3.0 has a very similar list. Some of these applications (such as Exchange Server 2013) are made compatible with a service pack. You will need to determine if a service pack or another fix is available for your particular application and situation.

The other issue you need to resolve is will the new version of Windows PowerShell break any of your existing code. Unfortunately, under some circumstances the answer will be, "Yes." You can find details in the Release Notes about any breaking changes that have been introduced.

The Windows PowerShell team has done an excellent job minimizing the number of breaking changes, but it is never possible to ensure that there aren’t any when a new version is created. The safest way to ensure that your code will run in a newer version of Windows PowerShell is to test it. Of course, being a Windows PowerShell user, you will want to automate those tests.

Assuming you’ve determined that your applications are compatible with the new version of Windows PowerShell, you need to determine the new features in which you are really interested. If you want the parallelization and ability to survive restarts, you need Windows PowerShell 3.0, and Windows PowerShell 4.0 would be better due to the enhancements.

Don’t try to convert all of your production scripts to new functionality as soon as you have the new version. A much better approach is to use the new functionality in new code. You can modify existing code as you make major modifications to your scripts and modules.

The machines you will be using to run Windows PowerShell have an impact on the version of Windows PowerShell you can use. Following are lists of appropriate operating systems for each version.

Windows PowerShell 4.0:

  • Windows Server 2012 R2
  • Windows Server 2012
  • Windows Server 2008 R2
  • Windows 8.1
  • Windows 7 with SP1

Windows PowerShell 3.0:

  • Windows Server 2012
  • Windows Server 2008 R2
  • Windows Server 2008 SP2
  • Windows 8
  • Windows 7 with SP1

For servers, the current pattern is Windows PowerShell version N is available for Windows Server version N to N-2, where N is the latest version. Client operating systems are slightly more complicated in that Windows PowerShell 4.0 isn’t available for Windows 8 (use the free upgrade to Windows 8.1), and Windows PowerShell 3.0 isn’t available for Windows Vista.

One other aspect to think about when considering operating systems is that a lot of Windows PowerShell functionality in Windows 8 and Windows Server 2012 is delivered as CDXML modules. These modules utilize the cmdlets over objects technology by starting with a CIM class, wrapping it in XML, and publishing the resulting .cdxml file as a Windows PowerShell module. If you install Windows PowerShell 4.0 on Windows 7, for instance, you won’t get that new functionality, which can amount to 60% of the cmdlet set.

The reason you won’t get the functionality is that the required CIM classes don’t exist on the older versions of Windows. The CDXML modules can’t access them, and therefore, they won’t work. They aren’t included in the download for the older operating systems to simplify matters. It’s better for them not to be present rather than present and not working. You also need the appropriate CIM class to be on any remote server you are trying to administer using those cmdlets.

If you are looking at upgrading the version of Windows PowerShell on your administration machine (workstation or server), I would recommend upgrading the operating system so that you get the maximum benefit.

If you are upgrading an existing server, I would actually question the need to perform an upgrade. The reason for this statement is that Windows PowerShell remoting is compatible across versions, so you can connect to and administer a machine running Windows PowerShell 2.0 from a machine running Windows PowerShell 4.0 (or any other combination of the versions discussed earlier).

One point to keep in mind is the version of WSMAN. It changed from 2.0 in Windows PowerShell 2.0 to 3.0 in Windows PowerShell 3.0. This mainly impacts the ability to use CIM sessions (analogous to Windows PowerShell remoting sessions, but used by the CIM cmdlets). They default to using WSMAN to connect to remote machines, but it has to be WSMAN 3.0. If your remote machine is running WSMAN 2.0 you will get an error message when trying to connect. The solution is to drop back to DCOM for the connection to those machines.

If you are building new servers, I would recommend installing the latest version of Windows PowerShell that is compatible with your version of the operating system. This ensures that you have the functionality if you need it.

One final thing you must never ever forget when upgrading: Ensure that everything goes through your organization’s change control process. It really will protect you if something goes wrong.

Upgrading the version of Windows PowerShell is a very interesting question, and as you have seen, there isn’t a right answer. The decision to upgrade has to be based on the circumstances of your organization and the systems involved. If you decide to perform an upgrade, please remember to test everything. I hope your upgrades go smoothly and you enjoy the new functionality.

Bye for now.

~Richard

Thanks, Richard. 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: Determine PowerShell Version on Your System

$
0
0

Summary: Learn how to determine the version of Windows PowerShell installed on your system.

Hey, Scripting Guy! Question How can I discover the version of Windows PowerShell that is installed on a particular system?  

Hey, Scripting Guy! Answer Use the $psversiontable built-in variable to get a display such as this:

Name                           Value

----                           -----

PSVersion                      4.0

WSManStackVersion              3.0

SerializationVersion           1.1.0.1

CLRVersion                     4.0.30319.34014

BuildVersion                   6.3.9600.17090

PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}

PSRemotingProtocolVersion      2.2

The first line of the results tells you the current Windows PowerShell version. This variable was introduced with
Windows PowerShell 2.0. If you get nothing back, it's Windows PowerShell 1.0.

Upgrade to PowerShell 4.0 Because It Is Easier to Use

$
0
0

Summary: Microsoft PowerShell MVP, Teresa Wilson (aka Scripting Wife), talks about upgrading to Windows PowerShell 4.0 because it is easier to use.

Microsoft Scripting Guy, Ed Wilson, is here. Today I continue my series of posts about upgrading to Windows PowerShell 4.0 by turning over the keyboard to Windows PowerShell MVP, Teresa Wilson. Teresa is also known as the Scripting Wife, and she is active in the Windows PowerShell community with events such as PowerShell Saturday, PowerShell User Groups, and PowerShell.org. Take it away Teresa...

Hi everyone. Teresa, aka Scripting Wife, is here. I know that everyone talks about Desired State Configuration (DSC) as the big exciting feature in Windows PowerShell 4.0. Perhaps if I worked on servers, I would agree. I have heard Ed come home many times complaining about how someone messed up a server by changing stuff that was not supposed to be changed. He also gripes about people ignoring change management procedures (whatever that is). So yeah, I guess it is a big deal.

But the reason I like Windows PowerShell 4.0 is simple—it is easier to use. Here are some of my favorite features in Windows PowerShell 4.0.

#requires

On my laptop, I run as a normal user. This is fine for a lot of things. I can even open the Windows PowerShell ISE and write a quick script—mostly this works. But there are issues. It seems that a lot of things in Windows PowerShell require Admin rights. So I have to start the Windows PowerShell ISE again with Admin rights. The problem with this is that lots of things do not really say, “Permission denied.” Instead they say something along the line of, “Resource failed to work” or simply “Get lost, Script Monkey.” I mean, really—how rude!

So when I figure out what happened (usually by asking the Scripting Guy), I like to make a note of it. With the new #requires feature, it is easy.

Image of command

Ignoring blank lines

One of the things that used to bug me (sort of) was that when I used Import-CSV, I had to make sure that my comma-separated value (CSV) file did not have any blank lines. If it did, things would simply blow up. I even had to ask Ed to write a post about cleaning out blank lines from text files (see Deleting Extra Returns and Line Feeds from a Text File Using Windows PowerShell).

Things for me got a lot easier for me when the Windows PowerShell team fixed the Import-CSV cmdlet so that it ignores blank lines when it imports stuff. This means that now when I import a .csv file, if it has blank lines, I do not get empty records, errors, and false things in the results. Sweet!

Image of file

Here is the import. Notice that the blank line is ignored.

Image of command output

A couple of other things

There are a couple of other things in Windows PowerShell 4.0, which for me personally, add up to a big deal. One thing is that when I use Get-Module, it now shows me the version. This is really cool for when I download modules from the Script Center Repository or some other place. It is not a big deal for things that come with Windows PowerShell—only for the modules I get from friends. Here is an example:

PS C:\> Get-Module PowerShellISEModule

 

ModuleType Version    Name                 ExportedCommands

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

Script     4.0        PowerShellISEModule     {Add-HeaderToScript, Add-Hel...

Another thing that I like is that when I use Remove-Item with the –Recurse switch, it now deletes things from subfolders. I think this was probably a bug fix because previously, it wouldn’t work, and I would think I was doing something wrong. It was pretty annoying. But now it works like I expect, and that is sweet.

For me, Windows PowerShell 4.0 is all about making things easier. But to be honest, it was not a big decision. I was already running Windows 8 on my new laptop, so when Windows 8.1 came out, of course I upgraded. And all of a sudden, now I am using Windows PowerShell 4.0. It was that easy. The fact that Windows 8.1 came with Windows PowerShell 4.0 was an unexpected bonus. I hope this helps when you are making your decision about upgrading.

~Teresa

Thank you, Teresa, for an interesting post. Upgrade to Windows PowerShell 4.0 Week will continue tomorrow when I will introduce another guest blogger.

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: Replace Characters in String that Is Not Part of Group

$
0
0

Summary: Use Windows PowerShell to replace all characters in a string that is not part of a group.

Hey, Scripting Guy! Question How can I use Windows PowerShell to remove all the non-alphabetic characters in the following string?
           (The single quotation marks are not part of the string.)

'({Abcde})'

Hey, Scripting Guy! Answer Create a regular expression pattern (character group) that includes the alphabetic characters a – z and A – Z,
           and use the "not in character group" operator (^) at the beginning of the pattern. Use the Windows PowerShell 
           -replace operator, and write the value back to the variable. Here is an example:

PS C:\> $a = '({Abcde})'

PS C:\> $a -replace '[^a-zA-Z]',''

Abcde

Note  This code uses single quotation marks. The replacement string uses two back-to-back single
quotation marks.

Practical Reasons for Upgrading to PowerShell 4.0

$
0
0

Summary: Guest blogger and Windows PowerShell MVP, Jeff Wouters, provides several practical reasons for upgrading to Windows PowerShell 4.0.

Microsoft Scripting Guy, Ed Wilson, is here. Today we continue our “Why Upgrade to Windows PowerShell 4.0” series with a guest blog post written by Jeff Wouters. Jeff is a Windows PowerShell MVP in the Netherlands, and he is a cofounder of the Dutch PowerShell User Group. Not only that, he is a great guy and a good friend to the Scripting Wife and me. Take it away Jeff...

When you are considering upgrading to a new version of Windows PowerShell and remaining on the same operating system version, keep in mind that some products only work with specific versions of Windows PowerShell.

When Windows PowerShell 3.0 came out, some people were installing it on many of their systems, and "suddenly" applications such as SQL Server, Sharepoint, and Exchange stopped working properly. This has a main technological explanation and a reason—which, in this case, are not the same.

History 101

The main technological explanation is that in Windows PowerShell 2.0, Microsoft was using the common language runtime (CLR), and in Windows PowerShell 3.0, they switched to using the dynamic language runtime (DLR). These are two fundamentally different technologies!

The CLR is the core set of services offered by the .NET Framework, such as a type system and a garbage collector. The DLR is built on the CLR, and it offers services for dynamic languages (such as dynamic types, dynamic method dispatching, and code generation).

The reason is that the people who installed Windows PowerShell 3.0 on those systems didn’t RTFM (read the f*ck*ng manual). The manuals for the applications that broke clearly stated that they were supported on Windows PowerShell 2.0. So those issues could have been avoided with some proper testing. The lesson is: Don’t introduce new software directly into your production environment—test it first.

Practical implementation

Here’s a common scenario that I also use: Upgrade your laptop, desktop, or server from where you run your scripts. Here you can use the full benefits of the latest and greatest release of Windows PowerShell. Then inside the scripts you’re running, use Windows PowerShell remoting to accomplish your tasks on specific endpoints. You don’t have to upgrade the Windows PowerShell versions on those endpoints, and therefore, you won’t break any applications that are installed.

That was a little history and practical information… now let’s go to the good stuff: Windows PowerShell 4.0.

Why upgrade?

Why should you upgrade? I’ll discuss some new features and enhancements that have been most important for me, and let you make up your own mind.

Desired State Configuration

To define the state of a type of server in a text file and let the server configure itself based on that definition, simply point the server to that definition and let it do the rest. For example, verify the configuration every XX minutes, and if the configuration doesn’t match the definition, let the server correct itself.

Because the definition is simply a text file, you can put versioning on it. There is no longer a need to give a lot of people local administrator rights on servers. Instead, edit the text file and wait for the server to compare itself again to the definition. That’s Desired State Configuration in Windows PowerShell, and what you can accomplish with it!

Workflow

Natively, Windows PowerShell does its tasks in sequence: 1 -> 2 -> 3 -> 4 ->…

Windows PowerShell Workflow is built on Windows Workflows, and it allows you to run tasks in parallel. For me, this has been very useful when running tasks across multiple endpoints. For example, I had a deployment script with 25+ separate tasks. The execution time went from 50+ minutes to about 20.
Now that’s what I like!

Get-FileHash

This new cmdlet returns a file hash in one of several formats for a specified file. It is very useful if you want to know if two files are different. It doesn’t compare the content of the file, but by comparing the hashes of two files, you can easily tell if the files are different.

RunNow parameter for scheduled jobs

Scheduled jobs were introduced in Windows PowerShell 3.0. However, when you created a new scheduled job and wanted it to start immediately, you had to define an immediate starting date and time for the job. In Windows PowerShell  4.0, there is a new parameter for the Register-ScheduledJob and Set-ScheduledJob cmdlets: –RunNow. This allows you to (guess what?)—run the scheduled job now!

RepeatIndefinetely

This parameter has been added to the New-JobTrigger and Set-JobTrigger cmdlets. Previously, you needed to specify a TimeSpan.MaxValue for the RepetitionDuration parameter to run a scheduled job for an indefinite period. The RepeatIndefinetely parameter has made this easier.

Get-Process shows user name

The Get-Process cmdlet now shows a IncludeUserName property. So now it’s rather easy to figure out who is running that process on a device or Remote Desktop Server!

DefaultCommandPrefix

Whenever the DefaultCommandPrefix is used in a module manifest in Windows PowerShell 4.0, the ExportedCommands property of the module shows the command in the module with the prefix. When you run the commands by using the module-qualified syntax, the command names must include the syntax. Useful, right?

If you don’t know why you should use a command prefix...

This makes your command unique and chances of having command name conflicts become smaller. A prefix usually consists of 2 or 3 characters.

Think about these enhancements, investigate what else is new in Windows PowerShell 4.0, and draw your own conclusions!

~Jeff

Thanks, Jeff! Why Upgrade to Windows PowerShell Week will continue tomorrow.

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 4.0 Where Operator to Filter

$
0
0

Summary: Use Windows PowerShell 4.0 Where operator to filter results.

Hey, Scripting Guy! Question How can I use a Where operator in Windows PowerShell (without using the pipeline or Where-Object)
           to filter through processes?

Hey, Scripting Guy! Answer Use Get-Process  to group the processes into a collection, then use the Where operator
           and filter on the process name, for example:

(Get-process).Where({$_.ProcessName -eq 'winlogon'})

My Path to a PowerShell 4.0 Upgrade

$
0
0

Summary: Microsoft IIS MVP, Terri Donahue, talks about her path to upgrading to Windows PowerShell 4.0.

Microsoft Scripting Guy, Ed Wilson, is here. Welcome new guest blogger, Terri Donahue.

Microsoft IIS MVP, Terri Donahue is a systems administrator who has been supporting Internet Information Services (IIS) since version 4.0. Through the years, she has had extensive hands-on experience with many web servers including Lotus Domino, Apache, and of course, IIS. She has a passion for helping people solve technology-related problems. She is focusing on improving her Windows PowerShell skills. She regularly attends the Charlotte PowerShell User Group and volunteers at PowerShell Saturday in Charlotte.

Take it away, Terri...

Windows PowerShell 4.0 is backward-compatible with Windows PowerShell 3.0 and Windows PowerShell 2.0. This means that upgrading to Windows PowerShell 4.0 should not be governed by the necessity to maintain multiple versions of scripts for the different versions of Windows PowerShell. The decision should be determined by the new features that PowerShell 4.0 can provide. Windows PowerShell 2.0 brought us remoting, and Windows PowerShell 3.0 brought us IntelliSense and lots of new cmdlets. As everyone has heard, Desired State Configuration (DSC), is the biggest addition to Windows PowerShell 4.0.

However, there are more new features in Windows PowerShell 4.0 than DSC. The Save-Help cmdlet can come in very handy for downloading a local copy of Help for a given module or modules for use on a computer that doesn’t have Internet access. I imagine this will be a bigger plus than is originally realized—as the offline Web PI command-line utility has been.

One thing to note is that upgrading to Windows PowerShell 4.0 does not ensure that all the new cmdlets will work exactly the same on the upgraded systems. This is the same issue that I encountered when I installed Windows Framework 3.0 on Windows Server 2008 R2. A script that correctly queried a certificate property on my computer running Windows 8 (native Windows PowerShell 3.0) returned the same status code regardless of the setting of the property on a server that had been upgraded to WMF 3.0.

To ensure that it was an operating system dependency rather than an issue with the cmdlet, I used the old school method of querying with crypt32.dll rather than the Windows PowerShell cmdlet. Both methods had the same results on the upgraded server running Windows Server 2008 R2.

I am an administrator who hacks around at script, including Windows PowerShell writing, so being able to debug my script is a necessity. The debugger has also been enhanced in Windows PowerShell 4.0. It now allows for debugging a script running on a remote computer, and it even preserves the debugging session when the remote session is disconnected and later reconnected.

Based on my research, I decided to upgrade my servers running Windows Server 2012 and Windows Server 2008 R2 to Windows PowerShell 4.0.

On a computer running Windows 8.1, there are 548 cmdlets. On a server running Windows Server 2012 R2, there are 693 cmdlets. As you can see from the following table, the number of cmdlets is greatly reduced when you perform an upgrade to a given Windows PowerShell version on a different operating system compared to the native installation on a computer. Therefore, that should not be the driving factor behind deciding to upgrade.

  Server version

  Cmdlets with WMF 3.0

  Cmdlets with WMF 4.0

  Windows Server 2008 R2

  313

  317

  Windows Server 2012

  440

  444

Be sure to read and follow the steps to install WMF 4.0 on your given operating system. I had no problem on my server running Windows Server 2008 R2, but on the server running Windows Server 2012, I kept running into this error message:

Windows update could not be installed because of error 2148098050 "The certificate for the signer of the message is invalid or not found."

The fix was to download the correct installer, which to me was not apparent. The the selected check box next to the installer name in the following image shows the correct installer for Windows Server 2012:

Image of list

The Windows8-RT naming convention was what threw me off. I kept trying to install the Windows6.1-KB2819745-x64.MultiPkg.msu package. In addition, I went so far as to install Windows Identity Foundation 3.5, which was referenced in many resolution articles—before I actually read the following steps in the release notes for Windows 2012:

Image of instructions

Sometimes, even some of us nerdy types need to be reminded to RTFM!

After the upgrade, I decided to play around with DSC some because I hadn’t seen it in action nor tried it. There were some frustrations when I was trying to get it to work as documented on a couple sites that I tried. I could not get it to create the .mof file, regardless of what I did. I went through a couple steps on the server running Windows Server 2012, and that still did not help. For example, I installed IIS and many of the features that I wanted to set up using DSC. I then installed Windows PowerShell Desired State Configuration (thinking that was the missing piece).

Image of menu

The step that I had been missing was actually running the configuration from the Windows PowerShell ISE. This loaded the configuration in the session. This is the same as running a function to initialize it before use. This is a configuration that installs all of the features I use in my IIS setups to ensure that certain components are available and ready for use:

Configuration TestWebsite

{

    param ($MachineName)

 

    Node $MachineName

    {

        #Install the IIS Role

        WindowsFeature IIS

        {

        Ensure = "Present"

        Name = "Web-Server"

        }

 

        #Install ASP.NET 4.5

        WindowsFeature ASP

        {

        Ensure = "Present"

        Name = "Web-Asp-Net45"

        }

 

        #Install Request Monitor

        WindowsFeature Request

        {

        Ensure = "Present"

        Name = "Web-Request-Monitor"

        }       

 

        #Install ODBC Logging - required for SMTP Server logging

        WindowsFeature ODBC

        {

        Ensure = "Present"

        Name = "Web-ODBC-Logging"

        }

 

        #Install Tracing - enables FRT

        WindowsFeature Tracing

        {

        Ensure = "Present"

        Name = "Web-HTTP-Tracing"

        }

 

        #Install ASP.Net 3.5

        WindowsFeature ASP35

        {

        Ensure = "Present"

        Name = "Web-ASP-Net"

        }

    }

As an explanation, each WindowsFeature designation installs the corresponding role or feature. This configuration installs the following features:

  • IIS
  • ASP.NET 4.5
  • Request monitoring
  • ODBC logging (which is required for the SMTP server)
  • Failed request logging (which, in my opinion, is essential to ensure that you can accurately trace error messages to resolve issues on your IIS implementation)
  • ASP.NET 3.5 to support any ASP.NET 2.0 applications that will be running on your IIS server

After entering this configuration in Windows PowerShell ISE, I saved the script as TestWebsite and then ran it. As shown in the following screenshots, the TestWebsite folder was created, and the .mof file was saved in it:

Image of menu

Image of menu

After you have initialized the configuration, you can run the Start-DscConfiguration cmdlet to implement the DSC configuration that you created earlier.

Image of command

The Start-DscConfiguration cmdlet requires a path to the folder that houses the .mof file. The Force parameter ensures that the configuration runs and the Verbose parameter writes the output to the console. Because this configuration has already been run on my server running Windows Server 2012, the following information is returned:

Image of command output

After I figured out this little nugget, I decided to try the same thing on my server running Windows Server 2008 R2, which had only WMF 4.0 installed. As you can see from the following screenshot, I have no roles installed.

Image of command output

I pasted the configuration in the Windows PowerShell ISE and ran it to initialize it. I then ran TestWebsite –MachineNamelocalhost. This ran the configuration with localhost as the $Machinename parameter. As shown here, after this ran, there is a TestWebsite folder created in the My Documents folder that has a localhost.mof file in it:

Image of command output

Image of menu

On this server, without all of the other attempts to resolve false issues, the command ran as expected. The output shows each feature being installed as it runs in addition to the successful installation and the amount of time to install each feature:

Image of command output

As you can see here, all requested features have been successfully installed and are ready for use:

Image of command output

Because IIS administration is what I do, this makes it easy to ensuring that installations include features that I deem as necessary on any machine that has Windows PowerShell 4.0 installed.

I hope you find this post useful when you are evaluating whether you should upgrade an existing Windows PowerShell 3.0 implementation to Windows PowerShell 4.0.

~Terri

Thank you, Terri, for an interesting and most excellent article. Windows PowerShell Upgrade Week will continue tomorrow when I will have a guest post by Windows PowerShell MVP, Dave Wyatt.

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 If PowerShell DSC Resource is Available

$
0
0

Summary: Learn to find if a Windows PowerShell DSC resource is available.

Hey, Scripting Guy! Question How can I find if the Desired State Configuration resource that I need for a script I found on the Internet is available
           on my computer?

Hey, Scripting Guy! Answer Use the Get-DSCResource cmdlet and specify the name of the provider. Here is an example that uses a standard
           DSC resource provider that should be available on a computer that runs Windows PowerShell 4.0.

PS C:\> Get-DscResource -Name file

ImplementedAs   Name                      Module                         Properties

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

Binary          File                                                     {Destina...

Viewing all 3333 articles
Browse latest View live




Latest Images