PowerShell for Windows Admins


November 11, 2014  1:00 PM

Transcripts

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

The ability to create transcripts of your PowerShell activity is great for keeping track of what you’ve done. They are also very useful when testing as you can keep a record of your results.

There’s one problem though – transcripts don’t work in the ISE.  Try this in PowerShell 4.0 or earlier:

Start-Transcript -Path C:\Temp\tran1.txt
Get-Process
Stop-Transcript

You’ll get an error like this:

Start-Transcript : This host does not support transcription.
At line:1 char:1
+ Start-Transcript -Path C:\Temp\tran1.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotImplemented: (:) [Start-Transcript], PSNotSup
portedException
+ FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.Start
TranscriptCommand

Your script will run then you’ll get another error:

Stop-Transcript : This host does not support transcription.
At line:3 char:1
+ Stop-Transcript
+ ~~~~~~~~~~~~~~~
+ CategoryInfo          : NotImplemented: (:) [Stop-Transcript], PSNotSupp
ortedException
+ FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.StopT
ranscriptCommand

 

Now try the same in PowerShell 5.0 and you’ll get this:

Transcript started, output file is C:\Temp\tran1.txt

 

Your script will run and you’ll see this at the end:

Transcript stopped, output file is C:\Temp\tran1.txt

 

Your transcript file will will be created and contain the desired output.

Another useful addition to your PowerShell tool kit – transcripts now work in ISE

November 9, 2014  11:50 AM

PowerShell classes – – static classes

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

A static class is one that you don’t need to create  an instance of the object to use – the [math] class provides many examples e.g.

£> [math]::pi
3.14159265358979

 

You can create a class with static methods using PowerShell classes:

class stest {

static [int] doubleup ([int] $in){

return $in * 2
}

}

 

Its used like this:

£> [stest]::doubleup(2)
4

 

Where could you use this – possibly to resolve look up values for instance when decoding WMI integer values or if you have a series of calculations you’ll be using in several select statements


November 4, 2014  12:27 PM

WMI integer properties – alternative decoding options

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell, WMI

 

WMI has many properties where the the value is an integer:

£> Get-CimInstance -ClassName Win32_LogicalDisk | Format-Table DeviceId, DriveType, Size, FreeSpace -a

DeviceId DriveType         Size    FreeSpace
——– ———         —-    ———
C:               3 135810510848 120492625920
D:               5

 

In the example drive type 3 is a standard hard disk and drive type 5 is defined as a compact disk

http://msdn.microsoft.com/en-us/library/aa394173%28v=vs.85%29.aspx

 

 

Remembering these can be a pain – there are a couple of ways to decode these values.

 

You could use a hash table – I showed many examples of this in PowerShell and WMI – www.manning.com/siddaway2

 

$dtype = DATA {ConvertFRom-StringData -StringData @’
3 = Hard Drive
5 = Compact Disk
‘@}
Get-CimInstance -ClassName Win32_LogicalDisk |
Format-Table DeviceId, DriveTYpe, @{N=’TYpe'; E={$dtype[“$($_.DriveType)”]}}, Size, FreeSpace –a

 

 

DeviceId DriveTYpe TYpe                 Size    FreeSpace
——– ——— —-                 —-    ———
C:               3 Hard Drive   135810510848 120495980544
D:               5 Compact Disk

 

 

Define the hash table via ConvertFrom-StringData . You can then just use the hash table as a look up to convert the numeric value of drive type into a descriptive name.

With WMF 5.0 and PowerShell classes there is another option

 

enum dtype {
HardDrive = 3
CompactDisk = 5
}

Get-CimInstance -ClassName Win32_LogicalDisk |
Format-Table DeviceId, DriveTYpe, @{N=’TYpe'; E={[dtype]$($_.DriveType)}}, Size, FreeSpace –a

 

DeviceId DriveTYpe        TYpe         Size    FreeSpace
——– ———        —-         —-    ———
C:               3   HardDrive 135810510848 120496607232
D:               5 CompactDisk

 

Create a enumeration using the enum keyword. The descriptive text CANNOT have spaces (delimited strings don’t work either). You can then substitute the enum value into your calculated field.


October 31, 2014  2:48 PM

DSC Resource Kit wave 8

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

Wave 8 has arrived and its massive with 48 new resources – that’s a 50%+ increase

http://blogs.msdn.com/b/powershell/archive/2014/10/28/powershell-dsc-reskit-wave-8-now-with-100-resources.aspx

 

New modules include:

  • xExchange
  • xSCDPM
  • xSCOM
  • xSCSMA
  • xSCSR
  • xSCVMM
  • xCredSSP
  • xDismFeature
  • xBitlocker
  • xPendingReboot


October 30, 2014  11:43 AM

PowerShell Summit NA 2015 – – Registration open

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

Registration for the PowerShell summit North America 2015 is open.  Details and registration link  – http://powershell.org/wp/community-events/summit/


October 29, 2014  1:56 PM

Cut and paste is not your friend

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

I was working on some code the other day and as a block of code I needed was very similar to one I already had I did what everyone does & used cut and paste. Unfortunately, I missed out changing one of the variable names in the new block and  spent a long time working out what had gone wrong.

 

Moral of the story – be careful how you copy code


October 29, 2014  11:41 AM

PowerShell in Depth second edition ebook

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

The ebook for PowerShell in Depth second edition is available from Manning – http://www.manning.com/jones6/


October 28, 2014  1:19 PM

JEA ToolKIt helper

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

JEA – Just Enough Admin – brings Role Based Access Control to Windows. It enables you to delegate specific cmdlets to specific users on specific endpoints.

A tool to help you create and mange JEA configurations is now available form

http://blogs.technet.com/b/privatecloud/archive/2014/10/24/introducing-the-jea-toolkit-helper.aspx

A white paper on JEA is also available from the same link


October 27, 2014  4:26 PM

PowerShell classes — using methods

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

.NET objects usually have methods as well as properties. A method enables you to do something to or with the object.  PowerShell classes can implement methods:

class LastBoot {
[string]$ComputerName
[DateTime]$LastBootime

## methods

[TimeSpan] Uptime([datetime]$lbt)
{
$ts = (Get-Date) – $lbt
return $ts
}

## constructors
LastBoot(){}

LastBoot([string]$computer, [DateTime]$lbt) {
$ComputerName = $computer
$LastBootime = $lbt
}

}

$comp = $env:COMPUTERNAME
$lbtime = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $comp |
select -ExpandProperty LastBootUpTime

$obj = [LastBoot]::new()
$obj | gm

$obj.Uptime($lbtime)

 

A method is defined like this:

[TimeSpan] Uptime([datetime]$lbt)
{
$ts = (Get-Date) – $lbt
return $ts
}

 

Give the type of the return value and the type and name of input parameters. If you don’t give an input type System.Object is assumed.

Write the code to perform the method’s action

 

use return to return the any values from the method. If your method doesn’t return anything then use a return type of [void] in the definition.

 

You must use return with a method. You can’t just put the object on the pipeline as you would with a function.

 

PowerShell classes are still a work in progress and you may see changes when we see the next preview


October 25, 2014  1:20 PM

PowerShell classes – – overloading constructors

Richard Siddaway Richard Siddaway Profile: Richard Siddaway
Powershell

You can usually create a .NET object from a class in one of several ways – no parameters i.e. and empty object up to an object with all of its properties populated as you create it. When you define a class you define the various ways in which it can be created – these are known as its constructors. When you have multiple constructors they are known as overloaded constructors i.e. a number of different ways to create the instance.

 

You have seen the default constructor in the previous post:

 

$obj = [LastBoot]::new()

 

You just use new() without any arguments to create the empty object which you then populate. If you know some of the values before you create the object you can use one of the overloads on the constructor to create the object:

 

$obj2 = [LastBoot]::new($comp, $lbtime)

 

Here you’re supplying the computername and last boot time as you create the object.  The class definition looks like this:

 

class LastBoot {
[string]$ComputerName
[string]$LastBootime

LastBoot(){}

LastBoot([string]$computer, [string]$lbt) {
$ComputerName = $computer
$LastBootime = $lbt
}

}

$comp = $env:COMPUTERNAME
$lbtime = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $comp |
select -ExpandProperty LastBootUpTime

 

$obj = [LastBoot]::new()

$obj.ComputerName = $comp
$obj.LastBootime = $lbtime

$obj

 

$obj2 = [LastBoot]::new($comp, $lbtime)
$obj2

 

Define the two properties as before. You have to explicitly define the default constructor when you are overloading the constructor:

 

LastBoot(){}

 

That says create a new instance of the LastBoot class but don’t set any properties.

 

Our overload:

LastBoot([string]$computer, [string]$lbt) {
$ComputerName = $computer
$LastBootime = $lbt
}

 

says create an instance of LAstBoot and I’m going to give you the computer name and last boot time. Map what you’re given to the ComputerName and LastBootime properties as shown.

 

Use the default constructor like this:

$obj = [LastBoot]::new()

 

And the overload like this

$obj2 = [LastBoot]::new($comp, $lbtime)

 

In case you’re wondering why this will useful to know – the simple answer is that you can create DSC resources using PowerShell classes which makes them much easier to write. But before we get to that you need to fully understand how PowerShell classes work.

 

Warning – PowerShell 5.0 is still in preview stage so this could 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: