Tag Archives: cmdlet series

PowerShell 2.0 One Cmdlet at a Time – Available as PDF download

If you have been following my blog for a while you will know that between November 2009 and July 2010 I ran a series of blog posts covering new cmdlets in PowerShell 2.0. I thought it would be useful to aggregate these posts into one document for reference purposes and so I have made this series available for download as a PDF.

You’ll be pleased to know I have spent many hours tidying it up, making links to other cmdlets internal to the document throughout and it has also been thoroughly reviewed by fellow PowerShell MVPs Thomas Lee , Richard Siddaway and Aleksandar Nikolic – I am most appreciative of their efforts in reviewing and the feedback given!

I hope you find this consolidated series useful. If you do then I ask that you consider making a small donation to a UK based charity that help the parents of children born with Tracheo-Oesophageal Fistula (TOF) and Oesophageal Atresia (OA). You can find out more about this charity through their website http://www.tofs.org.uk/index.php and can make a donation here http://www.justgiving.com/tofs/donate . I know from personal experience what a great job they do. Members of this charitable organisation condition are being particularly encouraged during October 2010 to raise awareness and funding so I hope you will help me in doing that.

PowerShell 2.0: One Cmdlet at a Time #107 Add-Type

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Add-Type cmdlet.

What can I do with it?

Imbed code from modern programming languages into your PowerShell session or scripts. The list of valid languages are: C#, C# 3.0, VisualBasic and JScript – C# is the default. Use the Language parameter to specify one if it is not C#.

Add-Type1

Example:

Within a PowerShell session use some C# code to create a TakeAway class and create a static method Minus. Use the Add-Type cmdlet to add the class to the session and then call the TakeAway class and Minus static method.

$csharp = @"
public class TakeAway
{
    public static int Minus(int a, int b)
    {
        return (a - b);
    }
}
"@
Add-Type -TypeDefinition $csharp
[TakeAway]::Minus(10,7)

You will see that we get the expected answer of 3:

Add-Type2

How could I have done this in PowerShell 1.0?

PowerShell 1.0 did not support adding C# or other code into PowerShell scripts, you could however have created your own cmdlet which I’m sure would have been very straightforward for most sysadmins :-)

1000 things 1% better!

PowerShell 2.0: One Cmdlet at a Time #106 Import-LocalizedData

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Import-LocalizedData cmdlet.

What can I do with it?

Enable text in scripts displayed to users to be presented in their own language. The cmdlet uses the automatic variable $PSUICulture to determine the language to use and alternate text is stored within .psd1 files in subdirectories of the folder that the script is stored.

Example:

In a script called RegionalTest.ps1 use the ConvertFrom-StringData cmdlet to create a series of text messages to display to the user. Import-LocalizedData will retrieve the value of the $PSUICulture automatic variable, get the contents of the RegionalTest.psd1 file in the es-ES directory (assume the user is Spanish) and store the data within the variable designated by the BindingVariable parameter. Then display the Welcome text.

$UserMessages = Data {
    # culture="en-US"
    ConvertFrom-StringData @'
    Welcome = Welcome to the application
    Error1 = You have entered an incorrect username
    Error2 = You have entered an incorrect password
'@
    }

Import-LocalizedData -BindingVariable $UserMessages

$UserMessages.Welcome

The contents of the RegionalTest.psd1 file for Spanish would look like (apologies for any bad translation!)

ConvertFrom-StringData @'
    Welcome = RecepciĆ³n al uso
    Error1 = Usted ha incorporado un username incorrecto
    Error2 = Usted ha incorporado una contraseƱa incorrecta
'@

and be stored in the es-ES folder below C:\Scripts where RegionalTest.ps1 lives

Import-LocalizedData

When run on the Spanish user’s machine the Spanish text would be displayed rather than the original English.

How could I have done this in PowerShell 1.0?

Script Internationalisation features were introduced in PowerShell 2.0 and not supported in version 1.0 – more info here.

1000 things 1% better!

PowerShell 2.0: One Cmdlet at a Time #105 Set-StrictMode

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Set-StrictMode cmdlet.

What can I do with it?

Configure strict mode for the current scope. An error will be generated when the content of an expression, script or script block violates coding rules. Note: it is possible to use the Version parameter to pick which coding rules to use. The PowerShell help lists the current possible options as:

1.0

— Prohibits references to uninitialized variables, except for uninitialized variables in strings.

2.0

— Prohibits references to uninitialized variables (including uninitialized variables in strings).

— Prohibits references to non-existent properties of an object.

— Prohibits function calls that use the syntax for calling methods.

— Prohibits a variable without a name (${}).

Latest

–Selects the latest (most strict) version available. Use this value to assure that scripts use the strictest available version, even when new versions are added to Windows PowerShell.

Example:

Examine what happens when you add the undefined $b to the undefined $a with strict mode off. Next, turn on strict mode using Version 1.0 and run the same test.

$a + $b
Set-StrictMode -Version 1.0
$a + $b

Note the error message generated with strict mode on because $a has not been initialised.

Set-StrictMode1

Examine what happens when you define $a to be a numerical value and attempt to reference a property with strict mode off. Next, turn on strict mode using Version 2.0 and run the same test.

$a = 32
$a.Time
Set-StrictMode -Version 2.0
$a.Time

Note the error message generated with strict mode on because the Time property does not exist.

Set-StrictMode2

How could I have done this in PowerShell 1.0?

You could have used Set-PSDebug, however Set-Strictmode applies only to the current scope or child scopes and does not impact the global scope. For more information on scopes in PowerShell look here.

1000 things 1% better!

PowerShell 2.0: One Cmdlet at a Time #104 Trace-Command

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Trace-Command cmdlet.

What can I do with it?

Begin a trace of a command or expression.

Example:

Examine debug info for Parameter Binding when piping a string through to Get-Service.

Trace-Command -Name ParameterBinding -Option All -Expression {'winmgmt' | Get-Service} -PSHost

You will see it is possible to work through the debug info to find out what is happening:

Trace-Command

Note: it is also possible to output the debug info to a file, simply remove the PSHost parameter and use FilePath instead.

Trace-Command -Name ParameterBinding -Option All -Expression {'winmgmt' | Get-Service} -FilePath C:\Debug.txt

The resulting debug info is now easily viewable in Notepad.

Trace-Command2

How could I have done this in PowerShell 1.0?

You could have used Set-TraceSource , but Trace-Command applies the trace only to the specified command.

1000 things 1% better!

PowerShell 2.0: One Cmdlet at a Time #103 Update-List

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Update-List cmdlet.

What can I do with it?

Add, Remove or Replace items from a property value of an object. This cmdlet can only update a property when it supports the IList interface. So far this does not include any of the core Windows PowerShell cmdlets – however it does include some of the cmdlets that ship with Exchange 2007 and later.

Example:

Add additional email addresses to the Test1 user’s mailbox using the Add parameter of Update-List.

Get-Mailbox Test1  | Update-List -Property EmailAddresses -Add admin@contoso.com,webmaster@contoso.com 
| Set-Mailbox

How could I have done this in PowerShell 1.0?

Shay Levy has a great blog post on dealing with AD / Mailbox accounts with multi-valued attributes.

1000 things 1% better!

PowerShell 2.0: One Cmdlet at a Time #102 Disable-PSRemoting

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Disable-PSRemoting function. Note: This is a proxy command which calls the Disable-PSSessionConfiguration cmdlet.

What can I do with it?

Disable PowerShell remoting on a computer that has previously been enabled for remoting. Note: This command must be run from a PowerShell session with administrative privileges.

Example:

Retrieve the current PSSessionConfiguration settings. Disable PowerShell remoting, then retrieve the PSSessionConfiguration settings again to compare.

Get-PSSessionConfiguration
Disable-PSRemoting
Get-PSSessionConfiguration

Notice the PSSessionConfiguration on a machine enabled for PowerShell remoting

Disable-PSRemoting1

Disable PowerShell Remoting. You will receive the following warning that using this command does not necessarily reverse everythign that Enable-PSRemoting may have done.

WARNING: Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or
Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps.
1. Stop and disable the WinRM service.
2. Delete the listener that accepts requests on any IP address.
3. Disable the firewall exceptions for WS-Management communications.
4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the
Administrators group on the computer.

Disable-PSRemoting2

Now check the impact on the PSSessionconfiguration – the AccessDenied permission has been applied to Everyone.

Disable-PSRemoting3

How could I have done this in PowerShell 1.0?

Remoting did not exist in PowerShell 1.0, you would have needed to use Remote Desktop to run an interactive session on a remote server.

1000 things 1% better!

PowerShell 2.0: One Cmdlet at a Time #101 Wait-Process

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Wait-Process cmdlet.

What can I do with it?

Wait for a process to stop before proceeding further.

Example:

Open an instance of Notepad. Use Wait-Process to pause the console session until Notepad is closed.

Notepad
Wait-Process -Name Notepad

You will notice that the console pauses whilst Notepad is open

Wait-Process1

Once Notepad is closed, control of the session is returned to the user.

Wait-Process2

How could I have done this in PowerShell 1.0?

Store the result of Get-Process Notepad in a variable, then use the WaitForExit method to wait for the process to stop.

Notepad
$Process = Get-Process Notepad
$Process.WaitForExit()

1000 things 1% better

PowerShell 2.0: One Cmdlet at a Time #100 Remove-Event

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Remove-Event cmdlet.

What can I do with it?

Delete an event from the current session. Note: to unsubscribe from an event you will need to use Unregister-Event.

Example:

Retrive current events in the queue with Get-Event, use Remove-Event to clear the event with the SourceIdentifier of Timer, then Get-Event again to confirm that it has been removed.

Get-Event
Remove-Event -SourceIdentifier Timer
Get-Event

You will see that the event has been cleared.

Remove-Event

How could I have done this in PowerShell 1.0?

PowerShell engine events are a new feature in PowerShell 2.0.

1000 things 1% better

PowerShell 2.0: One Cmdlet at a Time #99 Unregister-Event

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Unregister-Event cmdlet.

What can I do with it?

Clear an event subscription.

Example:

Use Get-EventSubscriber to retrive details of current events. Clear the event with subscription id 1 and Get-EventSubscriber again to confirm that it has been removed.

Get-EventSubscriber
Unregister-Event -SubscriptionId 1
Get-EventSubscriber

You will see that the event subscription has been cleared.

Unregister-Event

How could I have done this in PowerShell 1.0?

PowerShell engine events are a new feature in PowerShell 2.0.

1000 things 1% better