Coding Geekette

100% girl geek, all the time

PowerShell Not Your Father’s Command Line Part 15 of 31: ISE, ISE Baby…

Here’s hoping the PowerShell community doesn’t block me from their websites for my awful taste of music. ;)

Today’s topic is the ISE, the Integrated Scripting Environment. This PowerShell host application, written in WPF, is new as of PowerShell v2.0. In this post, we will look at some of my favorite features.

Panes

As one who writes script files more than just one-off commands, I like that the ISE has 3 panes – the Script Pane, the Command Pane, and the Output Pane. The order of these panes can be toggled from a menu or via keyboard shortcuts. Here are the basics of these panes:

  • Script Pane: This a pane dedicated to editing multi-line scripts. Some of the features I particularly am fond of with the Script Pane are syntax highlighting, debugging, and tab completion.
  • Command Pane: This is a pane dedicated to run commands on demand. Think of it as the console.
  • Output Pane: This is where the commands from the Command Pane and the scripts from the Script Pane output their results.

Keyboard Shortcuts

As a developer who prefers keyboard shortcuts rather than clicking buttons, I also am super happy that the shortcuts for running and debugging scripts in the ISE match up with keyboard shortcuts in Visual Studio. These are a few keyboard shortcuts that are the same:

  • F5 – Run
  • F9 – Toggle Breakpoint
  • F10 – Step Over
  • F11 – Step In
  • Shift + F11 – Step Out

Using the ISE as an Editor

In Matt’s post on profiles, he talked of editing the $profile file with notepad. For me, I tend to run the following command to the ise alias instead when I’m in the console:

ise $profile

The reason why I like the ISE for updating my profile files is because I have syntax highlighting, as seen below:
Sarah's console profile file in the scripts pane of the ISE

A Note on ISE Profiles

Applications that host PowerShell can implement any or all of the profiles. In my post on profiles, I noted that there were 4 console profiles. The ISE has 2 profiles of its own:

  • $profile, $profile.CurrentUserCurrentHost
  • $profile.AllUsersCurrentHost


This covers some of the basics of the ISE. If you want to learn more, you can run:

Get-Help about_Windows_PowerShell_ISE

No Comments »

PowerShell Not Your Father’s Command Line Part 14 of 31: Sorry I’m Not Home Right Now, Walking into IIS Webs…

Sorry I’m not home right now
Walking into IIS Webs
Just leave a message and I’ll call you back – No Doubt, if they were techies

So today we’re going to look into the IIS provider in PowerShell. If you aren’t familiar with PowerShell providers, check out Matt’s post on PowerShell providers. If you’re dealing with IIS 7.0, you’ll want to look into the IIS PowerShell snap-in. Otherwise, if you’re dealing with IIS 7.5, you’ll want to look into the IIS PowerShell module. Today’s post will be looking at IIS 7.5 and the WebAdministration module.

First things, first!

In order to work with the IIS module, you need to start a PowerShell session with elevated permissions. If you don’t, then you’ll get an error like this:

PS C:\users\sdutkiewicz:> Import-Module WebAdministration
Process should have elevated status to access IIS configuration data.

Once you start PowerShell as an administrator, you can use Get-Module to see if the WebAdministration module is loaded. If it isn’t loaded, then run:

Import-Module WebAdministration

The module is loaded. What kind of goodies are in the IIS module?

A lot of IIS functionality that you’re used to in the GUI is also available in the WebAdministration module, packed into a variety of cmdlets. There are cmdlets to help with:

  • web configuration
  • websites
  • web applications
  • application pools
  • web bindings

To see a full list of cmdlets, aliases, and functions included in the WebAdministration module, run the following command:

Get-Command -Module WebAdministration

You mentioned an IIS provider…

Yes, I did! If you run the following command, you’ll see a list of providers installed:

Get-PSProvider

You should see a provider named WebAdministration, which includes an IIS drive. Let’s see what it allows us to explore.

Set-Location IIS:

If we run a Get-ChildItem at this point, we’ll see that the IIS provider lets us navigate through 3 parts of IIS – AppPools, Sites, and SslBindings. Today, we’ll look at Sites, as they are the central point. The Sites folder in the IIS provider contains websites, web applications, and virtual directories. From the IIS: prompt, run the following command:

Set-Location Sites

If you run the Get-ChildItem command at this point, you should see the list of sites setup on your web server. It may look like the picture below:

Sarah's demo websites

You’ll notice that my sadukievents site shows a state of being stopped. We can easily fix this using one of the cmdlets included in the WebAdministration module:

Start-Website sadukievents

Notice how simple it was – no need to remember an IIS metabase path! Now let’s say that same site was getting carried away with the resources and we needed to stop the site. The Stop-Website cmdlet works similarly. Of course, sites rarely misbehave at an appropriate time. When you open PowerShell as an administrator, you’re dropped at your system folder (unless you’ve altered that). Rather than changing to the IIS drive and stopping the site (whose name you already know), you can run this command from your current drive with the following command:

Stop-Website sadukievents

Now back to IIS:\Sites… what do you see once you change directories into a Site? When you run Get-ChildItem (or its built-in alias of dir) on a site, it shows you the contents of the site. The image below shows what’s in the sadukievents website:

directory listing of the sadukievents website

You can see that the output from this particular folder looks like a directory listing – showing the file mode, last write time, length, and name. This appears this way because these are all files or directories. What if there was a virtual directory or possibly a web application in this folder? Then the output changes to show the type (application, directory, file, or virtualDirectory), name, and physical path. You can see a sample of this below:

directory listing of the sadukievents website with modules and virtual directories

At this point, you should feel comfortable navigating through the Sites folder. You can use Get-ChildItem and Set-Location to navigate through the AppPools and SslBindings folders in the same way, learning more about the AppPools and SslBindings.

So that’s navigation. Can we do anything else in here?

Besides navigating the IIS drive, you can also use it much like you would other PowerShell provider drives. When working with IIS cmdlets from outside of the IIS drive, you can reference the IIS drive as a path. For example, let’s say you’re working in a clustered web environment due to high-availability requirements and need to setup a new website on all the servers in the cluster. Sure, you could do it manually on each server, but why waste your time when you can script it? Here’s a sample command for creating a new web application:

New-Item ‘IIS:\Sites\Sadukieville’ -Type Application -PhysicalPath d:\Websites\Sadukieville

If that example web application had a virtual directory for a bakery site within it, it may be scripted like this:

New-Item ‘IIS:\Sites\Sadukieville\Bakery’ -Type VirtualDirectory -PhysicalPath c:\inetpub\wwwRoot\sadukieria

Both of the above examples show how you can use the IIS provider as a path with other cmdlets. Of course, there’s plenty more that you can do. For more information, explore the cmdlets as suggested above, and know that Get-Help and Get-Help command -examples are at your fingertips to guide you through how those cmdlets work and how you can take advantage of the IIS provider while scripting your web administration tasks.


Do you have specific questions about PowerShell that you want answered? Whether it’s IT pro related or developer related, I can probably help! Drop me a line at sarah at codinggeekette dot com, and I’ll try to cover your questions in an upcoming blog post.

Matt and I love feedback from our readers, so please email us if you have comments or suggestions.

No Comments »

PowerShell Not your Father’s Command Line Part 13 of 31: The Provider Active Directory Style

Matt and I really are huge fans of PowerShell providers. After talking about them in general and focusing on the registry provider, you think that we’d stop. But no… there are two more days of this talk of providers – Matt is going to talk about the Active Directory provider today, and I’m going to talk about the IIS provider tomorrow. Yes, providers make our administration tasks much easier by getting us access to things that are typically a little harder to script. This makes it easier for IT pros to write scripts that take advantage of these providers and automate more of their day-to-day operations.

Do you have a favorite provider? Tell us about it! Leave us comments on our blogs or email us. You can reach me at sarah at codinggeekette dot com.

No Comments »

PowerShell Not your Father’s Command Line Part 12 of 31: PowerShell and The Registry

Yesterday, Matt and I talked about providers, and I mentioned that I wasn’t going to go on talking about the registry provider, as that’s what Matt is talking about today! What’s nice is that you don’t have to type out HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER while working with this provider. You can refer to them by HKLM and HKCU, respectively.

However, those are the only 2 registry hives that are provided for. So if you are working with the other hives (HKEY_CLASSES_ROOT, HKEY_USERS, and HKEY_CURRENT_CONFIG), you will have to rely on your previous knowledge of accessing them to work with them. There are no HKCR, HKU, or HKCC drives to help out in this case.

No Comments »

PowerShell Not your Father’s Command Line Part 11 of 31: PowerShell Providers and You!

Today, Matt is going to tell you about the awesomeness known as PowerShell providers. I have to admit that providers really are helpful. Sure, there are the PowerShell-specific providers – Alias, Function, and Variable. These can tap into the PowerShell system and help you determine what aliases, functions, and variables already exist. But then there are other providers that are there to make it easier to access data stores that are typically hard to access in a scripting environment.

Matt will talk about the registry provider tomorrow, so I won’t go on about it here. The other built-in providers give us access to the file system objects (FileSystem provider), X.509 certificate store (Certificate provider), environment variables (Environment provider), and Web Services for Management (WSMan provider).

When Matt and I were working on our book, I had the joys of playing with providers and figuring out how they work under the covers. I won’t scare you off from them by showing you code here – that’s in Appendix C of our book. However, if you want to get into provider development more extensively after reading our book, I recommend talking with Oisin Grehan, the coordinator of the PowerShell Script Provider project on CodePlex, which will allow you to write a custom provider in PowerShell. (Yes, a provider to create providers!)

No Comments »

PowerShell Not your Father’s Command Line Part 10 of 31: PowerShell Protecting You From Yourself

Downloading PowerShell scripts from the Internet could be risky business if there were nefarious PowerShell scripters out there. Thankfully, there’s this thing called an execution policy that can protect us from running risky scripts when it is used properly. Today, Matt is writing about execution policies in PowerShell. Read it and understand it. You don’t want to run into trouble from a random PowerShell script.

If you find that you want to learn more on execution policies, be sure to check out:

Get-Help about_Execution_Policies

That help file has an extensive listing on execution policies, including covering the two policies (in addition to Restricted, AllSigned, RemoteSigned, and Unrestricted) that Matt didn’t mention (and with good reason). It also covers the precedence order in terms of group policies versus execution policies. It’s definitely worth the read if you’re in charge of securing your network and making sure that potentially dangerous scripts aren’t run haphazardly.

No Comments »

PowerShell Not your Father’s Command Line Part 9 of 31: Another Side of PowerShell Profiles

PowerShell profiles are a great way to load frequently used custom functions, variables, aliases, modules, and PowerShell objects every time you start PowerShell. Today, Matt will talked about how to setup your profile and some of the things you might put in your profile.

Matt mentions that there are 4 profiles – these are for the console. I qualify it at the console, as there are other profile variables that we’ll cover when we talk about the ISE later in the series. The 4 profiles though that he’s referring to can be edited following Matt’s guide and replacing $profile in his examples with any of the ones listed below:

  • $Profile, $Profile.CurrentUserCurrentHost
  • $Profile.CurrentUserAllHosts
  • $Profile.AllUsersCurrentHost
  • $Profile.AllUsersAllHosts

One other thing to note… Matt talks about creating a new profile with the -force option. However, you may have a profile in place already and may not want to overwrite it. If you want to see if the profile exists, use the Test-Path cmdlet:

Test-Path $profile

If the profile exists, then this will return True. Otherwise, it will return False.

As always, if you have any feedback for us, please send it along. We’ll hear what you have to say and may blog about a topic or suggestion!

1 Comment »

PowerShell Not Your Father’s Command Line Part 8 of 31: Won’t You Take Me To Functiontown? (Part 2)

In my last post, I mentioned getting a little further with functions by covering the runtime life cycle. Now, let’s go a little further and explore some of the arguments of the Parameter attribute, some additional attributes that can be used, and finally the CmdletBinding attribute.

Arguments of the Parameter attribute

When working with parameters in advanced functions, mark them with the Parameter attribute. This tells PowerShell that this is an advanced function and needs to be treated as such. This attribute can take a variety of arguments, including:

  • Mandatory – specifies whether the parameter is mandatory. If omitted, the parameter is not mandatory. Note that you need to specify that this equals $true, as this is not like a SwitchParameter.
  • Position – specifies where the parameter appears when it is used in a command
  • Help message – used with mandatory parameters, this tells the person calling the command what should be entered. This is useless for optional parameters.

Other Attributes

There are other attributes besides the Parameter attribute that you can use while working with advanced functions. There are attributes out there for aliases, validation, and dynamic parameters as well. The Alias attribute allows those entering a command to use a shortened alias for a parameter.

In terms of validation, you can validate to make sure inputs aren’t null, match a pattern, are within a range, allow nulls, and many other things.

The following code sample shows the Parameter, ValidateNotNullOrEmpty, and ValidateLength attributes in action, as well as some of the arguments for the Parameter attribute.

function Get-MaskedString{
param(
    [parameter(Mandatory=$true, Position=0,
    HelpMessage="Enter the string to be masked")]
    [string]
    [ValidateNotNullOrEmpty()]         
    $StringToMask, 
       
    [parameter(Position=1)]
    [string]    
    [ValidateLength(1,2)]  
    $MaskCharacter = '*'
    )
       
    Write-Host ($MaskCharacter * $StringToMask.Length)
}

Some things to note with the above code:

  • The Position argument is used on both parameters to control where they appear in a command. However, since the second parameter isn’t mandatory, it may or may not appear as part of the command.
    This is a valid command:

    Get-MaskedString ‘cake’

    This is also a valid command:

    Get-MaskedString ‘cake’ ‘§’

  • Since the ValidateNotNullOrEmpty attribute is used, the command will throw an error if it is fed an empty string. It will look like this:
    ValidateNotNullOrEmpty() error message
  • Since the ValidateLength attribute is used, the command will throw an error if $MaskCharacter is present and longer than 2 characters. In this example, 1 is the minimum length, and 2 is the maximum length. It will look like this:
    ValidateLength() error message
    However, this only validates when the $MaskCharacter is present. Otherwise, this parameter has a default value of ‘*’ and will use that if it isn’t present.
  • The HelpMessage argument is specified. This appears when you run the command and let it prompt you for the parameters and use ‘!?’ for help in the console, like this:
    ValidateNotNullOrEmpty() error message

CmdletBinding attribute

The CmdletBinding attribute gives advanced functions access to some functionality that a compiled cmdlet has access to – including SupportsShouldProcess, ConfirmImpact, and DefaultParameterSetName. ConfirmImpact works with the ShouldProcess in determining the impact of an operation. When SupportsShouldProcess and ConfirmImpact are used, the -whatif and -confirm parameters are unlocked.

Learning More

Note that these are just a few of the attributes and features of the CmdletBinding attribute. There are plenty more things you can do in advanced functions and with these attributes. If you really want to dig into writing advanced functions, you will also want to reference the following help topics:

about_functions_advanced
about_functions_advanced_methods
about_functions_advanced_parameters
about_functions_cmdletbindingattribute

1 Comment »

PowerShell Not Your Father’s Command Line Part 8 of 31: Won’t You Take Me To Functiontown?

Yesterday, Matt blogged about a basic PowerShell functions. I also have blogged in the past of some helpful functions that work with some of the PowerShell-specific providers. The code for those is fairly simple. However, functions aren’t always that simple; you can also write an advanced function, which runs similar to cmdlets.

Since advanced functions can be a large topic and some of this stuff overlaps with cmdlets, I am covering only a few of the topics in today’s posts.

Runtime Life Cycle
There are three phases that a function can go through:

  • Begin
  • Process
  • End

In PowerShell, Begin is run once, at the beginning of the function, before any pipeline objects are processed. Process is run for each object that is piped to that function. The automatic variable $_ is used for the individual pipeline object that is being processed during the Process phase. Once Process is finished, then End is run. Like Begin, End is run only once per function call.

If these keywords are left out, the advanced function’s normal processing behavior is treated like End.

Here is an example that uses all of these phases:

function Convert-FahrenheitToCelsius{
   begin{
      "Converting Fahrenheit input to Celsius:"
   }
   process {
      $degreesC = ($_ - 32)/1.8 
      "$_  degrees F = $degreesC degrees C"
   }
   end {
      "Done converting the input to Celsius"
   }
}

If I run the following command, I should get the following output.

Command

80, 32, 0  | Convert-FahrenheitToCelsius

Output

Converting Fahrenheit input to Celsius:
80  degrees F = 26.6666666666667 degrees C
32  degrees F = 0 degrees C
0  degrees F = -17.7777777777778 degrees C
Done converting the input to Celsius

Now since begin and end are only displaying strings and not handling the conversion, we can eliminate them. This would work just fine:

function Convert-FahrenheitToCelsius{
   process {
      $degreesC = ($_ - 32)/1.8 
      "$_  degrees F = $degreesC degrees C"
   }
}

Since the process keyword is present, the function will treat each of the pipeline objects individually. But what would it look like if we left off the process keyword?

function Convert-FahrenheitToCelsius{
   $degreesC = ($_ - 32)/1.8 
   "$_  degrees F = $degreesC degrees C"
}

The output for the sample command would be:

  degrees F = -17.7777777777778 degrees C

Notice that it didn’t treat the pipeline objects individually. This is probably not what you want, so if you’re going to pipe in objects that need to be treated individually, then the process keyword is needed.

This should give you an idea on the three phases that a function can go through. However, if you need more information on the runtime life cycle, you can find it by running:

Get-Help about_functions

You can also find out more about the Begin, Process, and End methods – in addition to many methids for confirmation, writing, error handling, and others – available to advanced functions by running:

Get-Help about_functions_advanced_methods

In the next post, later today, we will look at a few agruments of the Parameter attribute and mention the CmdletBinding attribute.

2 Comments »

PowerShell Not your Father’s Command Line Part 7 of 31: Conjunction Function PowerShell What Are Functions?

Thanks to Matt for getting “Conjunction Junction” stuck in my head. Today, he’s talking about functions in PowerShell. Check out his post, as he uncovers just what happens when you type c: and explains the basic differences between an alias and a function.

Then come back tomorrow as I’ll dive into functions a little more.

No Comments »