DiscoPosse – Using the chicken to measure IT
Technology, Cycling, Music and Madness


Technology

November 19, 2011

PowerShell One-Liners – Take my script, please!

More articles by »
Written by: Eric
Tags: , ,
Henny Youngman

“Doctor, my leg hurts. What can I do?” The doctor says, “Limp!”

Hail Henny Youngman, the king of one-liners! One of the great things about PowerShell is the ability to create simple, powerful one-line scripts. This is not to say that we need to crunch everything down to single line just to be cute, but we have the ability to build effective processes by making use of the pipeline.

With shell scripting, it’s often regarded as a number of processes that we pile together with inline code, but quite often we only have some small tasks that we need to run, but they require more than one action in the script.

Pipeline

The long and the short of it (emphasis on short) is that we can do a lot of things with a single line of code by leveraging the pipeline.

Here is an article about piping and the pipeline from Microsoft TechNet: http://technet.microsoft.com/en-us/library/ee176927.aspx 

The pipeline allows you to take some input, whether it is a file, or a query and then to perform a cumulative set of actions.

Let’s say I want to read the contents of a text file, and create an output file with only lines that contain the phrase “yourdomain.com”. To do this we use this simple one-line script:

Get-Content yourinputfile.txt | Where-Object {$_ -match ‘yourdomain.com’} | Out-File youroutputfile.txt

As you can see we are reading the file, applying a where clause to the input and then writing the output to a destination. This is a classic case of a pipeline by taking one object, processing it, and then outputting the processed content.

Let’s look at an example where we want to scan Active Directory users with the Quest ActiveRoles Get-QADUser CmdLet and output the Password status to screen but we want to exclude non-expiring passwords:

Get-QADUser -SizeLimit 0 | Select-Object samAccountName,mail,PasswordStatus | Where-Object {$_.PasswordStatus -ne “Password never expires” | Write-Host “$_.samAccountName status with email $_.mail has a password status of $_.PasswordStatus”

This script reads the directory, selects the fields we want and then outputs to screen for us using the Write-Host CmdLet. Simple and effective.

As you can see we can do many tasks where it is Input => Process => Output  and the Process step can contain many steps within it.

So what’s the downside? One-liners aren’t always appropriate for a few reasons. Primarily, if we need to loop through input multiple times, or parse the content, run complex calculations. Another reason is that we may be processing very large input which must reside in memory during the process which may require a more carefully designed script to include multiple loops and garbage collection during runtime.

This is an organic and dynamic article where I will collect my favorite one-liners by category over time. This is the starting point and I welcome you to add your own in the comments and I will be sure to add them to the collection.

Last updated on July 3, 2012

Exchange 2010

Query your Exchange servers for databases and file locations

Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize,EdbFilePath, | Export-Csv X:\MailboxDatabase.csv

Report Exchange 2010 Recipient Mailbox Policies (from @JeffHicks)

get-mailbox | sort RetentionPolicy | format-table -group RetentionPolicy

Query your Exchange server queues and show the message count as a point in time snapshot (from @HardcoreITGuy)

Get-exchangeserver | where {$_.isHubTransportServer –eq $true} | get-queue | where {$_.MessageCount –gt 0}

Windows

Find the installation date of Windows through WMI

 ([WMI]”).ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).InstallDate)

Active Directory

List computer object counts categorized by Operating System (uses Quest ActiveRoles snap in)

Get-QADComputer -sizeLimit 0 |  Group-Object -Property OSName,OSServicePack -noelement | Sort-Object -Property Count -Descending | Format-Table -Property Count,Name

 Export all XP Computers, with all properties into a CSV format sorted by IP Address

Get-ADComputer -Filter {OperatingSystem -like “Windows XP*”} -Properties * | sort-Object IPv4Address | Export-CSV XPComputers.csv

Export a list of all non-server OS computers into a CSV format where the computer account hasn’t contacted AD for over 30 days

get-adcomputer -Filter { OperatingSystem -notlike “Windows Server*” } -Properties PasswordLastSet | Where-Object { (((Get-Date) – $_.PasswordLastSet).Days) -gt 30} |  select-object Name, @{Name=”Age”;Expression={ (((Get-Date) – $_.PasswordLastSet).Days) }} | Export-CSV ComputerListByAge.csv

Much more to come so check back often and I’d love to have your contributions to add and share.



About the Author

Eric





 
 

 
featured_powershell

Updating (same as parent folder) records with DNSCMD and PowerShell

In an earlier post on the site (Microsoft DNS record updates using PowerShell and DNSCMD) I noted how PowerShell cannot natively update records in MS DNS, however we could leverage the DNSCMD command and pass parameters using a...
by Eric
1

 
 
featured_powershell

CSV, yeah you know me! – PowerShell and the Import-Csv CmdLet – Part 3

This was a long overdue post, so thanks for sticking with me while I finally got back on track with our CSV, yeah you know me series (Here are Part 1 and Part 2). As I’d mentioned in the closing of Part 2, we want to be a...
by Eric
0

 
 
featured_powershell

Finding RDP sessions on servers using PowerShell

Have you ever needed to use RDP to get to a server console for some local admin work and then been bounced out because there are already active sessions? Or have you had your Active Directory account locked out because of an op...
by Eric
8

 




Join Zipcar and get $50 in free driving Join Zipcar and get $50 in free driving Join Zipcar and get $50 in free driving

0 Comments


Be the first to comment!


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>