PowerShell for Windows Admins


July 20, 2011  3:09 PM

Can I? Should I?–examples–legacy scripts



Posted by: Richard Siddaway
PowerShell v2

In this post http://msmvps.com/blogs/richardsiddaway/archive/2011/07/17/can-i-should-i.aspx I stated that PowerShell isn’t necessarily the right answer to every problem.

I was left a comment asking if I could expand.  I’ll do that over a series of short posts as I think of examples.

One of the first that comes to mind is legacy scripts.

VBScript never really caught on as a mainstream administration tool. There were a number of reasons for this:

  • non interactive
  • harder to use and debug
  • less information
  • less flexible
  • admins addicted to the GUI
  • less pressure on people i.e. more admins

However, a number of organisations created a significant number of scripts and performed some very clever stuff.

Now, the question for those organisations is this -

“PowerShell has appeared. Do I convert all those scripts, that work really well to PowerShell?”

 

My answer would be no!  Learn PowerShell first . Get really proficient. Develop new stuff in PowerShell and migrate the legacy scripts when they need an over haul (or you get some free timeSurprised smile) that way you get the best of both worlds and run the smallest risk when you come to migrate the legacy scripts.

July 20, 2011  2:49 PM

July 2011–User Group reminder



Posted by: Richard Siddaway
PowerShell v2, User Group

Next Tuesday – 26 July there will be a UK user group session looking at PowerShell remoting:

  • cmdlets with remoting capabilities
  • .NET remoting capabilities
  • Invoke-Command
  • PowerShell sessions
  • WinRm and WSMan cmdlets

Details on joining the live meeting session:


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 18, 2011  12:36 PM

Joining objects



Posted by: Richard Siddaway
Network, PowerShell v2, WMI

PowerShell doesn’t have the equivalent of an SQL Union statement that lets you join objects together. What you can do is use New-Object to create the joined output.

As an example that recently came up on a forum

$outputs = @()            
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPenabled=$true" |            
foreach {            
 $nic = Get-WmiObject -Class Win32_NetworkAdapter -Filter "DeviceId='$($_.Index)'"            
            
 $output= New-Object -TypeName PSObject -Property @{            
  NICCardName = $nic.NetConnectionId            
  DHCPEnabled = $($_.DHCPEnabled)            
  IPAddress = $($_.IPAddress)            
  SubnetMask = $($_.IPSubnet)            
  Gateway = $($_.DefaultIPGateway)            
  DHCPServer = $($_.DHCPServer)            
  DNSDomain =  $($_.DNSDomain)            
  DNSDomainSuffixSearchOrder = $($_.DNSDomainSuffixSearchOrder)            
  DNSServerSearchOrder = $($_.DNSServerSearchOrder)            
 }             
$outputs += $output            
}            
$outputs

Get the NetworkAdapterConfigurations where they are IPenabled. Then for each get the associated adapter.

Create a new object and add the properties.  Add the object to the array of results.

At the end output the array.

I would not use the array and just output the object and allow the pipeline to take care of any other processing


July 17, 2011  4:17 AM

Can I? Should I?



Posted by: Richard Siddaway
Automation, PowerShell v2

The question “Can I do X with PowerShell?” comes up very frequently.

PowerShell provides access to a huge range of functionality:

  • .NET
  • COM
  • WMI
  • Microsoft and third party products

Usually the answer is “Yes, you can”

BUT

What doesn’t seem to be considered so often is the question “Should I do X with PowerShell?”

If you don’t have alternatives then by all means try it but if there are better ways to accomplish the task then consider them.

If all you have is PowerShell everything looks like a script


July 15, 2011  6:47 AM

Printer Security settings



Posted by: Richard Siddaway
Security, Shares, WMI

I was recently asked about getting the security settings for printers.

$pace = DATA {            
ConvertFrom-StringData -StringData @'
983052 = ManagePrinters
983088 = ManageDocuments
131080 = Print 
524288 = TakeOwnership
131072 = ReadPermissions
262144 = ChangePermissions 
'@            
}             
$flags = @(983052,983088, 131080, 524288, 131072, 262144)            
            
            
function get-printersecurity {            
 [CmdletBinding()]            
 param (            
  [string]$computer="."            
 )            
             
 Get-WmiObject -Class Win32_Printer -ComputerName $computer |            
 foreach {            
  "`nPrinter: $($_.DeviceId)"            
  $query = "ASSOCIATORS OF {Win32_Printer.DeviceID='$($_.DeviceID)'} WHERE ResultClass=Win32_Share"            
  Get-WmiObject -ComputerName $computer -Query $query |             
  foreach {            
    ""            
    "Share: $($_.Name)"            
                
    $query2 = "ASSOCIATORS OF {Win32_Share.Name='$($_.Name)'} WHERE ResultClass=Win32_LogicalShareSecuritySetting"            
    $sec = Get-WmiObject -ComputerName $computer -Query $query2            
    $sd = $sec.GetSecurityDescriptor()            
    $sd.Descriptor.DACL | foreach {            
      ""             
      "$($_.Trustee.Domain)  $($_.Trustee.Name)"            
                  
      foreach ($flag in $flags){            
        if ($_.AccessMask -band $flag){            
          $pace["$($flag)"]            
        }            
      }            
    }            
  }            
 }            
}

 

Create a hash table lookup and an array of flags

The function then gets all the printers on a system, links through to any shares and then gets the security descriptor of the share. The DACL on the security descriptor is iterated over to generate a list of users and their permissions


July 13, 2011  5:01 AM

European PowerShell Deep Dive



Posted by: Richard Siddaway
Deep dive, PowerShell

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



Posted by: Richard Siddaway
Books, Windows

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



Posted by: Richard Siddaway
Network

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



Posted by: Richard Siddaway
Disks

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



Posted by: Richard Siddaway
Disks

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


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: