PowerShell for Windows Admins


July 13, 2011  5:01 AM

European PowerShell Deep Dive

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

In April there was a Powershell Deep Dive at The Experts conference. It went
so well that the event is to be repeated at the European version of The Experts
Conference – October 17-18

Available details are limited but start here

http://blogs.msdn.com/b/powershell/archive/2011/07/12/powershell-deep-dive-the-experts-conference-europe-2011.aspx

July 13, 2011  2:55 AM

Windows SysInternals Administrators Reference

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Windows SysInternals Administrators Reference

Title: Windows SysInternals Administrators Reference

Publisher: Microsoft Press

ISBN: 978-0-7356-5672-7

The SysInternals tool set – http://technet.microsoft.com/en-us/sysinternals/default.aspx
 – should be one of a Windows administrator’s
best friends. You may not need them every day but when you do they will help dig
you out of the hole. The toolset was created, and is still maintained by Mark
Russinovich. Originally, offered as an independent set of utilities it is now
owned and supplied (as a free download) by Microsoft.  

One of the difficulties, with any troubleshooting toolset,
is knowing how to get the best out of the tools, especially if you are only
using them now and again. The SysInternals tools can be downloaded as a
complete suite or the individual tools (or group of tools) can be downloaded
independently. This approach leaves the administrator possibly using, and
understanding, part of the toolset because they are used regularly but
completely ignorant of the rest of the tools.  Mark Russininovich, and his co-author Aaron
Margois, have created the Windows SysInternals Administrators Reference to address
that gap

The book is divided into three parts:

·       
Part 1 starts with the SysInternals core
concepts, including some historical background. Chapter 2 follows on with a
look at Windows Core Concepts including administrative rights, process,
threads, user and kernel mode, handles, call stacks and sessions.

·       
Part 2 is where we dive into the toolset:

o  
Process Explorer

o  
Process Monitor

o  
Autoruns

o  
PsTools

o  
Process and Diagnostics Utilities

o  
Security Utilities

o  
Active Directory Utilities

o  
Desktop Utilities

o  
Network and Communications utilities

o  
System Information utilities

o  
Miscellaneous Utilities

·       
Part 3 looks at using the tools in some real
life scenarios

o  
Error messages

o  
Hangs and sluggish performance

o  
Malware

I suspect that many readers will read parts 1 and 3 for the
very valuable information. Part 2 is more of a reference which will be dipped
into as needed. The breadth of the SysInternals toolset means that you won’t be
using all of the tools all of the time but will need the information on using
the other tools. I would strongly recommend at least skimming through the
chapters in part 2. You may well find something that will help solve an
incipient problem. They can also suggest a course of action to help investigate
potential problems.

As a very strong advocate of using PowerShell there are some
occasions where the two sets of functionality overlap. The SysInternals tools
will often take over where the PowerShell functionality finishes so tend to be
complimentary rather then competing.

This is a book to which I think every Windows
administrator/consultant needs access. I tend to carry a netbook these days
with my library of scripts and utilities plus electronic copies of the
important reference works I might need. A copy of the latest version of the
SysInternals tools plus this book is very definitely included in that content.  

Highly recommended for all Windows administrators and
consultants. Don’t leave home without it.

 


July 9, 2011  6:45 AM

Linking the network card to the Registry settings

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

An interesting problem from the forum. Get the IP enabled network adapters and read the associated registry keys to get the value of the NetLuidIndex.

$HKLM = 2147483650            
$reg = [wmiclass]'\\.\root\default:StdRegprov'            
$keyroot = "SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}"            
$value = "NetLuidIndex"            
            
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled='$true'" |            
foreach {            
            
$data = $_.Caption -split "]"            
$suffix = $data[0].Substring(($data[0].length-4),4)            
$key = $keyroot + "\$suffix"            
            
$nli = $reg.GetDwordValue($HKLM, $key, $value)  ## REG_DWORD            
            
$nic = New-Object -TypeName PSObject -Property @{            
         Description = $_.Description            
         DeviceID = $_.Index               
         Suffix = $suffix            
         NetLuidIndex = $nli.uValue            
       }            
$nic            
} | Format-Table -AutoSize

Use the standard registry settings to read the HKLM hive and setup the WMI registry provider.

Get the network cards using a filter of IPEnabled = $true.

For each card break the caption property to get  the subkey value and add it to the key root. Do a standard DWORD read on the registry and construct an object to display the results


July 7, 2011  2:23 PM

Next partition

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I also need to generate a partition number for Mount-VHD

Similar idea but use the Win32_DiskPartition class

function get-nextpartition {            
            
$disk = Get-WmiObject -Class Win32_DiskPartition |            
sort Index -Descending |            
select -First 1 -Property Index            
            
$nextindex = ($disk.Index) + 1            
$nextindex            
            
}

The Index is an integer so we only need to add 1


July 7, 2011  2:18 PM

Next drive letter

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I’ve been working on using the Hyper-V PowerShell library and wanted to use the Mount-VHD function.  It wants a drive letter.  The library provides Get-FirstAvailableDriveLetter but what I want is actually the next letter in the sequence.  I want to avoid A & B to avoid confusion. So I needed a function to get the next drive letter

function get-nextdriveletter {            
            
$disk = Get-WmiObject -Class Win32_LogicalDisk |            
sort DeviceId -Descending |            
select -First 1 -Property DeviceID            
            
$letter = ($disk.DeviceID).Substring(0,1).ToUpper()            
if ($letter -eq "Z"){            
 Write-Host "No more drive letters available"            
}            
else {            
 $nextletter = [char](([byte][char]$letter) + 1)            
 $nextletter            
}            
            
}

Use WMI to get the last letter used – descending sort on DeviceID produces that. Take the letter, convert to a byte value, add 1 and convert back

Job done


July 7, 2011  2:12 PM

July User group meeting details–PowerShell Remoting

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


When: Tuesday, Jul 26, 2011 7:30 PM (BST)


Where:

*~*~*~*~*~*~*~*~*~*

A look at PowerShell Remoting using individual commands, Invoke-Command and PowerShell sessions. How to configure remoting and get the best out of it

Notes


Richard Siddaway has invited you to attend an online meeting using Live Meeting.
Join the meeting.
Audio Information
Computer Audio
To use computer audio, you need speakers and microphone, or a headset.
First Time Users:
To save time before the meeting, check your system to make sure it is ready to use Microsoft Office Live Meeting.
Troubleshooting
Unable to join the meeting? Follow these steps:

  1. Copy this address and paste it into your web browser:
    https://www.livemeeting.com/cc/usergroups/join
  2. Copy and paste the required information:
    Meeting ID: C7JCCP
    Entry Code: fKg^5N’,D
    Location: https://www.livemeeting.com/cc/usergroups

If you still cannot enter the meeting, contact support

Notice
Microsoft Office Live Meeting can be used to record meetings. By participating in this meeting, you agree that your communications may be monitored or recorded at any time during the meeting.


July 6, 2011  1:13 PM

PowerShell and WMI webcast

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I have been invited by PowerShell.com to give a webcast on 7 September 2011 @ 12 noon Central Time (6pm UK time).

The webcast is entitled Get the most from PowerShell and WMI

Register here

https://www2.gotomeeting.com/register/944144658


July 3, 2011  6:52 AM

Computer Report IV: Time server

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

The batch file uses

net time /querysntp

which displays the name of the Network Time Protocol (NTP) server currently configured for the local computer or the one specified in ComputerName.

Unfortunately /querysntp  has been deprecated in later versions of Windows.

In a domain we normally configure client and server machines to use the domain time synchronisation hierarchy rather than an external time source (the exception to this is the PDC emulator FSMO role holder in the root domain which is the top of hierarchy and synchronises externally)

Our test then should be to see if we are using a domain time synchronisation source or external. This information is held in the registry.

We need to look in HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\parameters.

The Type property tells us if we are using domain synchronisation (NT5DS) or and external server (NTP). The server( s ) are held in the NTPserver property.

We can amend our basic data function to read these registry keys

function get-basicdata{             
[CmdletBinding()]             
param (             
   [string]$computer="localhost"             
)             
BEGIN{}#begin             
PROCESS{            
            
Write-Verbose "Get Operating System"            
$os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer            
            
Write-Verbose "Get Computer System"            
$comp = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer            
            
Write-Verbose "Get IP Address"            
$ip = Test-Connection -ComputerName $computer -Count 1            
            
Write-Verbose "Read registry entry"            
$HKLM = 2147483650 #HKEY_LOCAL_MACHINE            
            
$reg = [wmiclass]"\\$computer\root\default:StdRegprov"            
$key = "SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\rdp-tcp"            
$value = "MinEncryptionLevel"            
$minlvl = $reg.GetDwordValue($HKLM, $key, $value)  ## REG_DWORD            
            
Write-Verbose "Create Object"            
$obj = New-Object -TypeName PSObject            
$obj |            
Add-Member -MemberType NoteProperty -Name OperatingSystem -Value $($os.Caption) -PassThru |            
Add-Member -MemberType NoteProperty -Name ServicePack    -Value $($os.CSDVersion) -PassThru |            
Add-Member -MemberType NoteProperty -Name Version       -Value $($os.Version) -PassThru |            
Add-Member -MemberType NoteProperty -Name Domain       -Value $($comp.Domain) -PassThru |            
Add-Member -MemberType NoteProperty -Name Name       -Value $($comp.Name) -PassThru |            
Add-Member -MemberType NoteProperty -Name IPv4Address -Value $($ip.IPV4Address.IPAddressToString) -PassThru |            
Add-Member -MemberType NoteProperty -Name MinEncrypt -Value $($minlvl.uValue)            
            
Write-Verbose "Read registry time entry"            
            
$key = "SYSTEM\CurrentControlSet\Services\W32Time\Parameters"            
            
$value = "Type"            
$type = $reg.GetStringValue($HKLM, $key, $value)  ## REG_SZ            
            
$value1 = "NtpServer"            
$NTPserver = $reg.GetStringValue($HKLM, $key, $value1)  ## REG_SZ            
            
switch ($type.svalue){            
 "NTP"  { $obj |            
          Add-Member -MemberType NoteProperty -Name TimeType -Value "External Server" -PassThru |            
          Add-Member -MemberType NoteProperty -Name TimeServer -Value $($NTPServer.svalue)            
         }            
 "NT5DS" { $obj |            
           Add-Member -MemberType NoteProperty -Name TimeType -Value "Domain" -PassThru |            
           Add-Member -MemberType NoteProperty -Name TimeServer -Value ""            
         }            
}            
            
$obj            
            
}#process             
END{}#end            
            
}

 

A switch statement is used to test the value of Type and the appropriate data is add to the object.

As before use

get-basicdata        

to generate output to screen or something like this

   get-basicdata | out-file basicdata.txt   

to create an output file


July 3, 2011  5:17 AM

Computer Report III: Eventlog service

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

The batch file has a separate report for event log service status

wmic service where name="EventLog" get Name, SystemName, StartMode, Status

PowerShell translation

Get-WmiObject -Class Win32_Service -Filter "Name=’Eventlog’" | Select Name, SystemName, StartMode, Status

 

This becomes a very simple function

function get-eventstate{             
[CmdletBinding()]             
param (             
   [string]$computer="localhost"            
)             
BEGIN{}#begin             
PROCESS{            
            
Write-Verbose "Get Service"            
Get-WmiObject -Class Win32_Service -Filter "Name='Eventlog'" -ComputerName $computer |             
Select Name, SystemName, StartMode, Status            
            
}#process             
END{}#end            
            
}

 

As with all of the functions we’ve seen in this series if you want the output on screen run as

get-eventstate

but if you want a file creating

get-eventstate | out-file c:\scripts\eventstate.txt


July 3, 2011  5:06 AM

Computer Report: II Service Information

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

 

The batch file retrieves service information using

wmic service where state="Running" get DisplayName, Caption

Direct PowerShell translation is this.

Get-WmiObject -Class Win32_Service -Filter "State=’Running’" | Select DisplayName, Caption

Couple of problems:

  1. DisplayName and Caption tend to show the same output
  2. What about services that aren’t running? A major problem could be resolved if you realised a service that should be running has stopped.

Lets change the WMI to

Get-WmiObject -Class Win32_Service | sort State | Select State, Name, Caption

When we create our function we can add a switch to restrict output to just running services if required

function get-servicestate{             
[CmdletBinding()]             
param (             
   [string]$computer="localhost",            
   [switch]$running             
)             
BEGIN{}#begin             
PROCESS{            
            
Write-Verbose "Get Services"            
$services = Get-WmiObject -Class Win32_Service -ComputerName $computer            
            
if ($running){            
  $services | where{$_.State -eq "Running"} | Select Name, Caption            
}            
else {            
  $services | sort State | Select State, Name, Caption            
}            
            
}#process             
END{}#end            
            
}

 

By fetching all of the service information we allow ourselves the ability to easily modify the output if requirements change


Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: