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.

$FrameworkDir=[Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
$NGENPath
=Join-Path$FrameworkDir‘ngen.exe’

[AppDomain]::CurrentDomain.GetAssemblies() |
  Select-Object-ExpandPropertyLocation|
  ForEach-Object {
&
$NGENPath“””$_”””
}

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()
PS
> $Domain.DomainControllers

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

$Domain.FindDomainController()

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

$Domain.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 {
$ErrorActionPreference=‘Stop’
  # 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 {
$ErrorActionPreference=‘Stop’
  netusernonexistent
2>&1  
# this
raises an error

  ipconfig
2>&1              
# 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
-List

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

 

PSGet-WmiObject-Namespaceroot\SecurityCenter2-ClassAntivirusProduct

__GENUS                                             : 2
__CLASS                                             : AntiVirusProduct
__SUPERCLASS
                                :
__DYNASTY                                        : AntiVirusProduct
__RELPATH
                                        : AntiVirusProduct.instanceGuid=“{108DAC43-C256-20B7-BB05-914135
                                                                     DA5160}
__PROPERTY_COUNT                      : 5
__DERIVATION                                 : {}
__SERVER                                            : TOBIASAIR1
__NAMESPACE
                                    : ROOT\SecurityCenter2
__PATH                                                 : \\TOBIASAIR1\ROOT\SecurityCenter2:AntiVirusProduct.instanceGui
                                                                      d=“{108DAC43-C256-20B7-BB05-914135DA5160}”
displayName                                     : MicrosoftSecurityEssentials
instanceGuid
                                  : {108DAC43C25620B7BB05914135DA5160}
pathToSignedProductExe        : C:\ProgramFiles\MicrosoftSecurityClient\msseces.exe
pathToSignedReportingExe : C:\ProgramFiles\MicrosoftSecurity
                                                                        Client\Antimalware\MsMpEng.exe
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)
$xml=New-ObjectXML
    $xml.Load($PathXML)
$StringWriter=New-ObjectSystem.IO.StringWriter
    $XmlWriter=New-ObjectSystem.XMl.XmlTextWriter$StringWriter
    $xmlWriter.Formatting=“indented”
    $xmlWriter.Indentation=$Indent
    $xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
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:

 

functionSendText($Text=‘Sample
Text’
,
$Port=2500) {
$endpoint=New-ObjectSystem.Net.IPEndPoint ([IPAddress]::Loopback,$Port)
$udpclient=New-ObjectSystem.Net.Sockets.UdpClient
    $bytes=[Text.Encoding]::ASCII.GetBytes($Text)
$bytesSent=$udpclient.Send($bytes,$bytes.length,$endpoint)
$udpclient.Close()
}

 

functionStart-Listen($Port=2500) {
$endpoint=New-ObjectSystem.Net.IPEndPoint ([IPAddress]::Any,$Port)
$udpclient=New-ObjectSystem.Net.Sockets.UdpClient$Port
    $content=$udpclient.Receive([ref]$endpoint)
[
Text.Encoding]::ASCII.GetString($content)
}

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:

facebook
|
twitter
|
linkedin

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 {
param($Path)

    $present= @(Get-WmiObjectWin32_Networkconnection|
       Select-Object-ExpandPropertyRemoteName)

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

    } else {
netuse*$Path
    }
}

Jan 202012
 

PowerTip of the Day, from PowerShell.com:

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:

Get-WmiObject-ListWin32_*network*

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

Get-WmiObjectWin32_NetworkAdapterConfiguration

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 PowerShell.com:

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

Get-Process|Out-GridView

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:

Import-ModuleServerManager

Add-WindowsFeaturePowerShell-ISE