Getting a list of users in your AD domain via Powershell

Get-ADUser -Filter * -Properties HomeDirectory,LastLogonDate | Select-Object Name, LastLogonDate, HomeDirectory

will cause the following to display

Name       LastLogonDate          HomeDirectory
----       ---------------------  ---------------

CollinsP   11/12/2015 6:04:12 AM  \\\HomeDrive\CollinsP
SprouleK   19/12/2015 2:08:12 PM  \\\HomeDrive\SprouleK
ReithP     23/12/2015 8:45:54 PM  \\\HomeDrive\ReithP

How to output to a file?
Get-ADUser –Filter * -Properties HomeDirectory,LastLogonDate | Select-Object Name, LastLogonDate, HomeDirectory | Export-CSV 'c:\temp\AllDomainUserNames.CSV'

This article seem familar?  That will be because I wrote how to do this with Quest Active Server Roles Powershell Module, back in 2010.

The Microsoft page on Get-ADUser is here.

Getting a list of printers published in an Active Directory domain

So I need to get a list of print servers and printers in the domain.

Using Powershell.

Looking around the interwebs, I found a PowerShell commandline here which formed the basis of this commandline:
Get-ADObject -LDAPFilter "(objectCategory=printQueue)" -Properties cn, drivername, location, printername, portname, servername | select portname, cn, drivername, location, printername, servername | Format-Table -Property * -AutoSize | Out-String -Width 4096 | Out-File C:\wisefaq\printerlist.txt

Which outputs to a text file, like this:
portname cn drivername location printername servername
-------- -- ---------- -------- ----------- ----------
{} PRT001-LZR960-2 Dataproducts LZR 960 PS US/UT/Boort/99 Anytown St LZR960-2
{} PRT001-LZR960-1 Dataproducts LZR 960 PS US/UT/Boort/99 Anytown St LZR960-1
{} PRT001-LZR960-3 Dataproducts LZR 960 PCL US/UT/Boort/99 Anytown St LZR960-3
{} PRT001-LZR960-4 Dataproducts LZR 960 PS US/UT/Boort/99 Anytown St LZR960-4
{} PRT001-LZR960-5 Dataproducts LZR 960 PCL US/UT/Boort/99 Anytown St LZR960-5

So why did I use Out-File instead of Export-CSV?
Export-CSV is refusing to output the {ip.addresses}. I don’t know why, and I’ve wasted an hour trying to work around the issue.

Update: December 2015
Adrian suggests that I could use Powershell Custom Objects to fix the issue of ip.addresses not outputting.

PowerShell Quick Tip: Creating wide tables with PowerShell

Searching for Specific Printers in a Domain (Attributes for the printQueue Object)

Print-Queue class

PowerShell print server inventory script (looks very useful, but you need admin access to each of the printers)

Some PowerShell links

A slowly growing collection of PowerShell resources and links.

Books & guides
Microsoft Sweden – Sweden PowerShell course books and sample
Microsoft Technet – The VBScript-to-Windows PowerShell Conversion Guide
Quest – iPowerShell (PowerShell reference for the iPhone)
Quest – PowerShell TFM v1 ebook
Quest – Windows PowerShell v2 Help

Not free
Ed Wilson (the Microsoft Scripting Guy) – Windows PowerShell Scripting Guide


Cmdlets & modules etc.

Microsoft MSDN – PowerShell Pack
Quest – Free PowerShell Commands for Active Directory (sample use here)


Interesting & useful links
Microsoft Bing – custom PowerShell search
Microsoft Technet – Scripting Centre
Microsoft Virtual PC Guy – Using Alternate Credentials with WMI and PowerShell [Hyper-V]

Microsoft Jose Barreto’s Blog – How to Handle NTFS Folder Permissions, Security Descriptors and ACLs in PowerShell

Here (scripts)
Checking for existence of a file on a remote computer
Count files in a directory
CPU Utilisation
Pinging a computer
Reading last line of a file
Reboot remote computers
SMS 2003 & SCCM 2007 Server health checking

Bookmark and Share


Last Tuesday I blogged about the great free scripting tools from Sapien.  Well here’s another set of free tools/modules/call them what you will, from Microsoft.

The Windows 7 Resource Kit PowerShell Pack!  From the Microsoft MSDN Code Gallery:

About the Windows 7 Resource Kit PowerShell Pack

The Windows 7 Resource Kit PowersShell Pack is a collection of Windows PowerShell scripts included with the Resource Kit. The PowerShell Pack comes in the form of several Windows PowerShell modules, each containing anywhere from 3 to 600 functions.

To get started with the PowerShell pack, run InstallPowerShellPack.cmd from the directory on the CD, open up Windows PowerShell, and run Import-Module PowerShellPack . After you run this command, you will have hundreds of PowerShell scripts loaded to play with.

The Windows 7 Resource Kit PowerShell Pack contains 10 modules to do all sorts of interesting things with PowerShell. Import-Module PowerShellPack actually imports 10 modules for you to use. Here’s a brief overview of each of the modules.

Module Description
WPK Create rich user interfaces quick and easily from Windows PowerShell. Think HTA, but easy. Over 600 scripts to help you build quick user interfaces
TaskScheduler List scheduled tasks, create or delete tasks
FileSystem Monitor files and folders, check for duplicate files, and check disk space
IsePack Supercharge your scripting in the Integrated Scripting Environment with over 35 shortcuts
DotNet Explore loaded types, find commands that can work with a type, and explore how you can use PowerShell, DotNet and COM together
PSImageTools Convert, rotate, scale, and crop images and get image metadata
PSRSS Harness the FeedStore from PowerShell
PSSystemTools Get Operating System or Hardware Information
PSUserTools Get the users on a system, check for elevation, and start-processaadministrator
PSCodeGen Generates PowerShell scripts, C# code, and P/Invoke


While you might not use all of these modules in every situation, they represent solid families of commands you can use in any PowerShell scripts you like. The examples below should also help you start to “think in PowerShell”. Most of the tasks you will do in Powershell will not use a single command, but will instead combine many commands in one or more pipelines to get the job done. Each step of these pipelines is a rich object, with properties, methods, and events. This set of commands gives you a number of tools for working with some rich objects that were already lying in the operating system, just waiting for you to discover.

You can download the PowerShell pack here.

Bookmark and Share

Some great free scripting tools.

PrimalScript_box Sapien make, what I think is the best script editor available.  It’s called PrimalScript.  Not cheap, but it was the only way I know to step though a PowerShell script.  That’s changed with PowerShell 2, with it’s ISE.  But I’m still sticking with PrimalScript.

Sapien make a number of free tools available, and since I believe they preserve a wider audience, see below.

Continue reading

Check the health of your SMS 2003 & 2007 servers

I run a PowerShell script which checks the health of my 20 SMS 2003 servers.

Sure, I could install Microsoft Operations Manager (Microsoft MOM).  But there is the cost for the physical server, and Microsoft licensing to be considered.

So, instead I make do with the PowerShell script.  It’s saved me from having several server problems becoming noticeable to the customers.  (the latest example is here)

It’s crude, but it checks each of the SMS servers for:

  1. the server is alive, aka “pingable”.
  2. it’s CPU utilisation is <= 20%, and that no individual processor is running at greater than 20%.
  3. that the assorted SMS directories (inbox, Offersum etc.) are being processed.
    If a directory has greater than x files, this may be an problem.
    Curiously enough, Microsoft suggests a 10,000 file threshold.  I set it at 200 files.
  4. enough disk space exists on the SMS package shares.

Future plans?

  1. Write each check out to a log, for availability reporting.
  2. Check for “older than x days” files in the SMS directories.
  3. Make it’s output pretty, most likely via WPF.

You can download the script, and the sample server list file here.

Bookmark and Share

Getting CPU Utilisation with PowerShell

PowerShell logoI use the following piece of code in my “Check SMS Server are healthly” PowerShell scripts.  I had a case recently where the SQL Server process decided to use 80% of one CPU.  This script would have detected that problem.

$server_name = “WISEFAQDC”
$percentage_warn = 50

$cpuinfo = Get-WmiObject -ComputerName $server_name Win32_Processor

$count = 0
$cpu_utilisation_total = 0
$cpu_utilisation_average = 0
$cpu_utilisation_maximum_single_processor = 0

foreach ($cpu in $cpuinfo)
    $cpu_utilisation_total = $cpu_utilisation_total + $cpu.LoadPercentage
    $count = $count + 1
    if ($cpu.LoadPercentage -gt $cpu_utilisation_maximum_single_processor)
        $cpu_utilisation_maximum_single_processor = $cpu.LoadPercentage
$cpu_utilisation_average = $cpu_utilisation_total / $count

if ($cpu_utilisation_average -gt $percentage_warn)
    Write-Host "Server: $server_name - CPU load $cpu_utilisation_average %"
if ($cpu_utilisation_maximum_single_processor -gt $percentage_warn)
    Write-Host "Server: $server_name - Single CPU load, highest percentage is: $cpu_utilisation_maximum_single_processor %"

The output is:
Server: WISEFAQDC - CPU load 54 %
Server: WISEFAQDC - Single CPU load, highest percentage is: 82 %

There is a bug though, with Windows 2000 servers always reporting 98% utilisation.  Microsoft released hotfix KB 880086 to fix the problem.

Bookmark and Share

And here’s the PowerShell: Pinging a computer script

PowerShell logo

The first thing you might notice is that the PowerShell version is a bit shorter. 3 lines of VBscript code, compared to 1 line of PowerShell script. That is, 1 line of code to do the actual ping.

And here is a short program which demonstrates how to use PowerShell to ping a computer:

$computer_name = "WISEFAQDC"

$address_string = "Address=" + "'" + $computer_name +"'"
$ping = Get-WmiObject -Class Win32_PingStatus -Filter $address_string
if ($ping.StatusCode -ne 0)
    # the check -ne 0 means the ping check failed.
    Write-Host Server: $computer_name - Not pingable
    # the computer is visible on the network.
    Write-Host Server: $computer_name - is alive

Bookmark and Share

PowerShell: Reboot remote computers

PowerShell logo

It looks like it’s going to be a week of scripting blog posts.  Today’s script is used to reboot a list of remote computers.  Sometimes, when deploying security patches, the computers fails to reboot.  So I use this script to force reboots.  It would be a piece of cake to modify the script, so that it turns off the computers instead.

One of my customers should find that useful.  Out of 2000 computers, about 150 computers get left powered on over the weekend.

What the script does:

  • reads the list of computers to be reset from C:\computer_lists\reboot_target_list.txt
    the format of the list is COMPUTERNAME,Reboot Reason
  • “Pings” the computer to see if it’s on the network.
  • checks to see if someone is logged on.  If someone is, don’t reboot.
  • reboots the computer.

Check and reboot computers.ps1

Continue reading