May 212012

Optimizing PowerShell Performance

PowerShell is loading .NET assemblies. These assemblies can be pre-compiled using the tool ngen.exe which improves loading times (because the DLLs no longer have to be compiled each time they are loaded).

Before you think about optimizing the DLLs PowerShell uses, you should do some reading on ngen.exe and its benefits. Then, you could use the following code to optimize all DLLs loaded by PowerShell. You do need Administrator privileges for this.


[AppDomain]::CurrentDomain.GetAssemblies() |
  ForEach-Object {

May 162012

Finding Domain Controllers with Powershell

If your computer is logged on to an Active Directory, here is some code to get to your domain controllers. Note that this will raise errors if you are currently not logged on to a domain.

PS> $Domain= [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
> $Domain.DomainControllers

This lists all domain controllers. To find just one, try this:


And to find all the domain controllers in your forest, simply retrieve all forest domains:


May 152012

Executing Commands in Groups with Powershell

In traditional batch files, you can use “&&” to execute a second command only if the first one worked. In PowerShell, the same can be achieved by using the try/catch construct. You just need to know some little tricks. Take a look at this:


try {
  # commands follow
catch {}

Now, if you want to execute a group of command and abort everything once an error occurs, simply place the commands inside the try block. If the commands are native console commands, add a “2>&1” to each command.


try {
# this
raises an error

# this
will not execute due to the previous error

catch {}

Try and replace “nonexistent ” with an existing local user account such as “Administrator”, and you’ll see that ipconfig will execute.

May 142012

Listing All WMI Namespaces with PowerShell

WMI is organized into namespaces which work similar to sub-folders. Here’s a line that lists all namespaces you got:

PSGet-WmiObject -Query “Select *
from __Namespace”
 -Namespace Root | Select-Object -ExpandProperty Name

Next, you could investigate all classes that live in one of these particular namespaces:


PS> Get-WmiObject-NamespaceSecurityCenter2

And then, once you know the classes, you could retrieve information, for example, about your installed AntiVirus protection:



__GENUS                                             : 2
__CLASS                                             : AntiVirusProduct
__DYNASTY                                        : AntiVirusProduct
                                        : AntiVirusProduct.instanceGuid=“{108DAC43-C256-20B7-BB05-914135
__PROPERTY_COUNT                      : 5
__DERIVATION                                 : {}
__SERVER                                            : TOBIASAIR1
                                    : ROOT\SecurityCenter2
__PATH                                                 : \\TOBIASAIR1\ROOT\SecurityCenter2:AntiVirusProduct.instanceGui
displayName                                     : MicrosoftSecurityEssentials
                                  : {108DAC43C25620B7BB05914135DA5160}
pathToSignedProductExe        : C:\ProgramFiles\MicrosoftSecurityClient\msseces.exe
pathToSignedReportingExe : C:\ProgramFiles\MicrosoftSecurity
productState                                   : 397312
PSComputerName                              : TOBIASAIR1

May 142012

Formatting XML Files with Powershell

Here’s a cool little XML formatting tool. It takes the path to any XML file and allows you to specify an indent. Then, it saves the file as new XML file with the indentation you specified.

Here’s the code for the function:

functionFormat-Xml  {
param($PathXML, $Indent=2, $Destination=$env:temp\out.xml, [switch]$Open)
Set-Content-Value ($StringWriter.ToString()) -Path$Destination
    if ($Open) { notepad$Destination }

And this is how you’d use it:

PS> Format-Xml-PathXMLC:\Windows\Ultimate.xml-Open-Indent 1
PS> Format-Xml-PathXMLC:\Windows\Ultimate.xml-Open-Indent 5

Because of -Open, the result is opened automatically in Notepad, and you can see the results of the different indentation settings. To save the formatted XML to another place, use the -Destination parameter and specify a path and name for the XML file to be created.

May 092012


Communicating Between Multiple PowerShells via UDP

Assume you want to send some information to another PowerShell session, or you’d like to have one session wait until another is ready. Here are two simple functions that allow you to send and receive text information across PowerShell sessions using UDP:


$Port=2500) {
$endpoint=New-ObjectSystem.Net.IPEndPoint ([IPAddress]::Loopback,$Port)


functionStart-Listen($Port=2500) {
$endpoint=New-ObjectSystem.Net.IPEndPoint ([IPAddress]::Any,$Port)

Try it and launch two PowerShell consoles. Execute this code in both of them. Then, in one session call Start-Listen. Optionally you can change the network port.

The session now waits on the port specified. In your other shell, call this to wake up the listening shell and send over some text:

PS> Send-Text‘Hello
Wake Up!’

Share this tip on:


May 022012

Map Network Drive with Powershell

Sure you can use the command net use to map a network drive. But this would not check for existing mapped drives. Here’s a small function that first checks to see that the URL you are mapping to does not yet exist, avoiding duplicate mapped drives:


functionNew-MapDrive {

    $present= @(Get-WmiObjectWin32_Networkconnection|

    if ($present-contains$Path) {
“Network connection to
$Path is already present”

    } else {

Jan 202012

PowerTip of the Day, from

WMI is a great information resource, and Get-WmiObject makes it easy to retrieve WMI instances. First, use -List parameter to find WMI class names. For example, find classes that deal with network:


Next, pick one of the classes and enumerate its instances:


With WQL, a SQL-type query language for WMI, you can even create more sophisticated queries, such as:

Get-WmiObject-Query‘Select * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=True’

Dec 072011

Powershell V2.0 is the current latest realease [Dec 2011], installed by default on Windows 7 and Windows Server 2008 R2; and also available for download for earlier versions of Windows both 32bit and 64bit platforms.

On Windows 7, click the Start icon, All Programs, Accessories, “Windows PowerShell” folder
or Winkey+R type Powershell and enter

Windows Powershell is basically a CLI [Command Line Interface] like cmd but much more advanced

So Powershell is a task automation framework, cosisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems.

In PowerShell, administrative tasks are generally performed by cmdlets (pronounced command-lets), specialized .NET classes implementing a particular operation. Sets of cmdlets may be combined together in scripts, executables (which are standalone applications), or by instantiating regular .NET classes (or WMI/COM Objects). These work by accessing data in different data stores, like the filesystem or registry, which are made available to the PowerShell runtime via Windows PowerShell providers.

Windows PowerShell also provides a hosting mechanism with which the Windows PowerShell runtime can be embedded inside other applications. These applications then leverage Windows PowerShell functionality to implement certain operations, including those exposed via the graphical interface. This capability has been utilized by Microsoft Exchange Server 2007 to expose its management functionality as PowerShell cmdlets and providers and implement the graphical management tools as PowerShell hosts which invoke the necessary cmdlets. Other Microsoft applications including Microsoft SQL Server 2008 also expose their management interface via PowerShell cmdlets. With PowerShell, graphical interface-based management applications on Windows are layered on top of Windows PowerShell. A PowerShell scripting interface for Windows products is mandated by the Common Engineering Criteria.



Dec 072011

PowerTip of the Day, from

Out-GridView is a great way to present results in a “mini-Excel” sheet:


However, Out-GridView has two requirements:.NET Framework 3.5.1 and the built-in script editor ISE must both be installed. ISE is not installed by default on Windows Servers. So, if you want  to use Out-GridView on server products, you will need to make sure you install the ISE feature.

On a Server 2008 R2, you could enable ISE by using PowerShell: