July 2009 - Posts

PowerShell in Practice Ch14&15

The latest MEAP for PowerShell in Practice adds chapters 14 and 15 to the set. The book is essentially complete now – with just the appendix and the stuff at the front to do

It can be obtained from www.manning.com/siddaway

Technorati Tags:
Posted by RichardSiddaway | with no comments
Filed under:

Its a wrap

When we run a cmdlet such as Get-EventLog we often find that the display is truncated

PS> Get-EventLog -LogName Application | select -First 5

  Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
   12961 Jul 31 12:39  Information Com4QLBEx                       0 The description for Event ID '0' in Source 'Com...
   12960 Jul 31 12:39  Information hpqwmiex                        0 The description for Event ID '0' in Source 'hpq...
   12959 Jul 31 12:39  Information Wlclntfy               2147489648 The winlogon notification subscriber <SessionEn...
   12958 Jul 31 12:39  Information Winlogon               1073745925 Windows license validated.
   12957 Jul 31 12:01  Information Windows Error Rep...         1001 Fault bucket , type 0...

If we we need to actually need to see the full information we need to use format-table

PS> Get-EventLog -LogName Application | select -First 2 | Format-Table -Wrap

   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
   12962 Jul 31 12:44  Information HHCTRL                       1904 The description for Event ID '1904' in Source 'HHC
                                                                     TRL' cannot be found.  The local computer may not
                                                                     have the necessary registry information or message
                                                                      DLL files to display the message, or you may not
                                                                     have permission to access them.  The following inf
                                                                     ormation is part of the event:'about:blank', 'http
                                                                     ://go.microsoft.com/fwlink?LinkID=45840'
   12961 Jul 31 12:39  Information Com4QLBEx                       0 The description for Event ID '0' in Source 'Com4QL
                                                                     BEx' cannot be found.  The local computer may not
                                                                     have the necessary registry information or message
                                                                      DLL files to display the message, or you may not
                                                                     have permission to access them.  The following inf
                                                                     ormation is part of the event:'Service started'

The –wrap parameter gives us the capability to display the full data.  This parameter is also available in v1.

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

Services and Processes

Services and processes seem to be a constant source of topics for PowerShell.  Probably because they are so fundamental to Windows. I wanted to see the relationship between a service and its underlying process.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
##Requires -version 2.0
## create empty array
$data = @()
## create class for object
$source=@"
public class ServProc
{
    private string _servicename;
    private string _displayname;
    private string _processname;
    private int _processid;
    
     public string DisplayName {
        get {return _displayname;}
         set {_displayname = value;}
    }
    
    public string ServiceName {
        get {return _servicename;}
         set {_servicename = value;}
    }
    
    public string ProcessName {
        get {return _processname;}
         set {_processname = value;}
    }
    
    public int ProcessId {
        get {return _processid;}
         set {_processid = value;}
    }
}
"@

Add-Type -TypeDefinition $source

Get-WmiObject -Class Win32_Service | foreach {
    $sp = New-Object -TypeName ServProc
    $sp.displayname = $_.displayname
    $sp.ServiceName = $_.Name
    $sp.ProcessId = $_.ProcessId
    $sp.ProcessName = (Get-Process -Id $($sp.ProcessId)).Name

    $data += $sp

}
$data | Sort processid | Format-Table -AutoSize

 

What we need to do is get the services and find the process id and use that to match it to the underlying process.  This sort of problem I would usually create an object and then  use add-member to  add the properties as we loop through the services.

I decided to have a go with Add-Type instead.

Add-Type is cmdlet new to PowerShell version 2. If you are not a programmer you possibly looked at the help information, shuddered and moved on.  I have done a bit of C# programming but don’t class myself as a programmer (bet all programmers reading this are looking at the class definition as saying – yep). As far as I’m concerned if it works its good.

So we start with Requires so that don’t try and run this in version 1.

We can then create an empty array. So far so good.

The next bit is where we create a .NET class. A class is what we use when we create an object – think of it in this case as a template.  The stuff in the here string   $source=@”………..”@ is the C# code that defines the class.

public means that we can access it.  ServProc is its name.  We then have four properties which are created

public  string DisplayName    {
    get {return _displayname;}
     set {_displayname = value;}
}

by supplying a name eg Displayname and a data type eg string.  We also supply a get and set which do what they say.  Set is usewd when we set the property and get when we read it.  The

private string _displayname;

in effect defines a private variable that is used inside the class. C# IS CASE SENSITIVE!!! and expects a ; as a line terminator

Add-Type is used to create the class.

The Win32_Service WMI class can be used to get the service side information. We create a new object using our class and then set the properties. Notice that we can use the properties of the object as soon as we have created it to get the process name.

Our object is added to the array and we loop for the next service.

Final line of the script displays the data .

The hardest part of using add-type is remembering how to define the properties in C#.  Is it worth doing this compared to Add-Member?

It makes the working part of the script neater but makes the earlier part more complicated.  If you are not  happy with C# probably not for you though other languages can be used. On the other hand if all you want is an object with some properties you have a template here that can be re-used. Just create a private variable for each property and make sure you get the data type right.

Will I use this instead of Add-Member – probably. Especially where I am creating a module with a number of functions that will use the same object.

It wasn’t as difficult as I thought – but I would definitely put this in the advanced PowerShell bucket for now.

Posted by RichardSiddaway | with no comments
Filed under:

User Group Live Meetings

I’ll be doing a couple of Live Meeting webcasts over the next few weeks:

  • PowerShell remoting – including Exchange 2010
  • WMI in PowerShell v2

More info when the dates are finalised.

If there is a particular topic that you would like to see covered please let me know

Technorati Tags:
Posted by RichardSiddaway | with no comments

Tombstone Periods

We can get the tombstone period of our Active Directory by

001
002
003
$root = [ADSI]"" 
$ds = [ADSI]("LDAP://CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration," + $root.DistinguishedName)
$ds.tombstoneLifeTime

 

But if the value isn't set it means we are using the default which changes depending on the version of Windows used to create the forest in the first place. If we have upgraded then the value may not be what we think it is.

So far I haven’t found a way to get the original version of Windows used to create the forest.  It may not be possible in which case time for a rethink

PowerShell 2.0 ETA

In case you wanted more info on when we can see PowerShell v2 available as a download for XP\2003\Vista\2008  - see  http://blogs.msdn.com/powershell/archive/2009/07/23/windows-powershell-2-0-rtm.aspx

The post says a few months before we can get it.  Why the delay?

Best guess is that the PowerShell Team have been concentrating on Windows 7\2008 R2 and that the final testing, fixing and packaging needs to be done for the other platforms.  Remember how the Vista install package for PowerShell v1 came out  a couple of months after the other versions.

Patience is a virtue – so I’m told.

All good things come to he who waits.

On the other hand – I can’t wait.

Technorati Tags:
Posted by RichardSiddaway | with no comments
Filed under:

July User Group slides and demo

I’ve put the slides and demo file on my Sky Drive

http://cid-43cfa46a74cf3e96.skydrive.live.com/browse.aspx/PowerShell%20User%20Group

and download the July_2009 zip file

Enjoy

Posted by RichardSiddaway | with no comments

Today’s the day the gremlins have their picnic

So the story so far.

Our intrepid presenter is sent to the wilds of Northern England and must deliver the Live Meeting to the PowerShell UG from his hotle room.  No problem.

First problem is that the network in the hotel isn’t playing the game  (thats English understatement for broken).  It will occassionally let him connect but not won’t connect to any of the interesting sites on the Internet. No! Not that sort of interesting.  Interesting as is useful like hotmail or blogs of even Live Meeting.

All the usual attempts were made to rectify the problem – try another machine, try a different time, try different part of hotel Eventually the evil deed could be postponed no longer…….  the help desk had to be rung  <gulp>

One quick restart of the router and connection is made. Whew.

Same problem Tuesday, and Wednesday. This isn’t good news.  Ring help desk again and explain sweetly how much pain they are causing – OK you know me too well – Ring up,  have major rant and give up.

Why during all this can I still connect to work email – I’m not paranoid they are out to get me.

Thursday morning connectivity looks good & can connect. Just to be safe email friends and arrange for someone to to explain circumstances if can’t connect.

Thursday evening – connectivity is good, Live Meeting is good, upload slides, share PowerShell and start.  YeeHa.

Spoke too soon.

40 minutes into the session my laptop blue screens (my first ever blue screen on Windows 7 – unbelievable!!)  Why do demos always go wrong???

Quick phone call to get Jonathan to explain whats happening while I frantically re-connect

Finish demo

Finish Q&A.  All done. Time for a beer.

Thank you to those who attended and apologies again for the glitch.  Hope you can make it for the next session.

Technorati Tags:
Posted by RichardSiddaway | with no comments

Good news

There’s good news – Windows 7 and Windows 2008 R2 went RTM yesterday.  Look for downloads early next month for TechNet\MSDN subscribers. General availability is 22 October.

But there’s more

Windows 7 and Windows 2008 R2 contain PowerShell v2 – hurrah.  Turned on by default.  Even better.

But there’s more

PowerShell v2 will soon be available for other systems. – Hurrah, hurrah

Posted by RichardSiddaway | with no comments
Filed under:

Excel 2010 PowerShell I

This now works for a non-US locale.

001
002
003
004
$xl = New-Object -ComObject "Excel.Application"
$xl.visible = $true
$wb = $xl.workbooks
$wb.Add()

 

Well to be strictly correct it works in a UK locale and I’m assuming it works for other non-US locales.  As previous versions of Excel threw a wobbly and we had to use an awful work around this is a step forward.

Now we need true PowerShell support for Office :-)

I know the OpenXml PowerShell functionality has been extended.  Time to try that against Office 2010

Technorati Tags: ,
Posted by RichardSiddaway | 1 comment(s)
Filed under:

MDT 2010 supports PowerShell

MDT -  Microsoft Deployment Toolkit (was known as BDD in a previous life)  now supports PowerShell with a snapin to give a provider and some cmdlets.  See http://blogs.technet.com/mniehaus/archive/2009/07/10/mdt-2010-new-feature-16-powershell-support.aspx

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

Maths Functions

I’ve needed to access the maths functions in .NET for a few things recently and finally decided to create functions for the ones I use all the time.  I’ve started with 3 functions and put them into a module. The good thing about this is that I can easily load them dynamically and any other modules I create can load this module.

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
#Requires -version 2.0
function pi {
    [System.Math]::PI
}
function power {
    param ([double]$a, [double]$b)
    [System.Math]::Pow($a, $b)
}
function sqrt {
    param ([double]$a)
    [System.Math]::Sqrt($a)
}
function pi {
    [System.Math]::PI
}

 

Three functions defined so far. 

pi returns the value of PI – 3.142…..

power raises a number to a particular power so

$x = power 3 3

is equivalent to 3*3*3

sqrt returns the square root of the number

if you want other roots use

power 1000 (1/3) to get the cube root – replace 3 by whatever root is required

I’ll add a few more tomorrow.

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

PowerShell Editing

I have been a fan of the PowerGUI editor since it was first in beta but one thing has been consistently annoying.  I don’t like the way is sets itself as the default editor for PowerShell files and blocks changes to this unless you go into the registry and kill the keys it has set.

Bad PowerGUI!

Let me decide what I want to use to edit a particular file.  There are times when I want or need to use ISE. Don’t get in my way.

Technorati Tags: ,
Posted by RichardSiddaway | 5 comment(s)
Filed under: ,

PowerShell in Practice - Chapter 15

The last chapter – Chapter 15 - has been delivered for first pass editing. This is an extra chapter we decided to add to round off a few topics we thought should be included. Hopefully it will available on MEAP fairly soon.

Posted by RichardSiddaway | with no comments
Filed under:

Two recommendations

I took delivery of a copy of the Hyper-V Resource Kit today.  Only had chance to flick through it but Chapter 16 jumped out at me – Hyper-V Management using Windows PowerShell – unless my powers of deduction are way off this chapter was written by James O’Neill who also wrote the Hyper-V management library that is featured in the chapter – the code is available on codeplex.  I’ve finally had chance to start using it and its turning out to be as good as I expected and knowing James I expected a lot – nice one James.

The book was delivered by Computer Manuals - http://www.compman.co.uk/

Ordered it late yesterday afternoon and it arrives today while I was work.  That’s service. 

Posted by RichardSiddaway | with no comments
Filed under:

July User group meeting

This months meeting will be virtual.  I will arrange another virtual meeting for late August. 

We should have a physical meeting in September


When: Thursday, Jul 23, 2009 7:00 PM (BST)


Where: Virtual

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

Subject is PowerShell output. What we see. What we get. How we can change it. methods of output

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: 94F2K5
    Entry Code: q.bhRK7Hs
    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.

Posted by RichardSiddaway | with no comments

Amazon

My book has appeared on Amazon’s listings

http://www.amazon.co.uk/Powershell-Practice-Richard-Siddaway/dp/1935182005/ref=sr_1_1?ie=UTF8&s=books&qid=1246906667&sr=1-1

http://www.amazon.com/Powershell-Practice-Richard-Siddaway/dp/1935182005/ref=sr_1_1?ie=UTF8&s=books&qid=1246906789&sr=1-1

The dates are slightly optimistic   :-)

Thats nice.  Just need to finish the last chapter and it enters the final phase

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

Playing with dates

I happened to notice that Sundays date was 5 July 2009.  Not particular astute you may think but I noticed it because I’d written it as 5/7/9.  English date format puts the day then the month so this may not make sense in other formats.

The fact that there was a difference to two between the day and the month and the same between the month and the year intrigued me.  It doesn’t take much. So I decided to look at other dates that follow that pattern

001
002
003
004
for ($i=3; $i -le 12; $i++){
    $date = Get-Date -Month $i -Day $($i -2) -Year $(2000 + $i +2)
    "{0} {1}" -f $date.DayOfWeek, $date.ToShortDateString()   
}

 

It doesn’t need much to do this.  A for loop – notice we start at 3 so we don’t get into negative days. Time travel by PowerShell now there’s a thought

Get-Date | Set-Now –Era Jurassic

gets us back to the dinosaurs.  OK I’ll stop.

We can use Get-Date and give it a month, day and year to create the date.  Note that I add 2000 to get the current sequence of dates. This sequence will happen every century.  One thing I noticed was that Get-Date takes the year you give it literally.  It doesn’t make any allowance for the century if you don’t supply the full year.  Compare

PS> Get-Date -Day 1 -Month 1 -Year 9

01 January 0009 19:46:48

PS> [datetime]"1/1/9"

01 January 2009 00:00:00

Finally I use a formatted string to display the date (in short form) and the day of the week.  The day of week doesn’t appear to add any more information but I was curious.

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

DHCP cmdlets

Documentation on TechNet states that there are cmdlets for managing DHCP servers on Windows 2008 R2.  This appears to be an error as there is no sign of them after installing DHCP.

Technorati Tags:
Posted by RichardSiddaway | with no comments
Filed under:

HP G60

I am currently using a HP G60 laptop.  Runs Windows 7 very well. I created a dual boot environment so I could install Windows 2008 R2 and to my pleasant surprise found Hyper-V runs on it.  Need to enable virtualisation in the BIOS but apart from that slight hiccup it installs and works very well.  Once I get the RTM version it will be time to finally abandon Virtual PC.

Also gives me a chance to play with James’ Hyper-V library.

Technorati Tags:
Posted by RichardSiddaway | with no comments
Filed under:
More Posts Next page »