January 4, 2016  9:29 AM

## Starting to use PowerShell

Profile: Richard Siddaway
Powershell

A common question goes along the lines of  “I’ve leant PowerShell (from class, book etc) but what do I do next?”

The usual answer is to pick a problem in your organisation and solve it.

I’ve provided an example in this UK TechNet blog post

http://blogs.technet.com/b/uktechnet/archive/2016/01/04/starting-your-powershell-journey.aspx

Its the second one of a series on PowerShell

January 2, 2016  10:34 AM

## 2015 December Scripting Games Puzzle

Profile: Richard Siddaway
Powershell

The December 2015 puzzle was based on the 12 Days of Christmas song.  Starting with this here-string.

\$list = @”
1 Partridge in a pear tree
2 Turtle Doves
3 French Hens
4 Calling Birds
5 Golden Rings
6 Geese a laying
7 Swans a swimming
8 Maids a milking
10 Lords a leaping
11 Pipers piping
12 Drummers drumming
“@

A here-string is a multiline string. It is NOT an array – its a single string. The first task is to  split into an array of individual lines:

## split into individual lines
\$s = \$list -split ‘\n’

Each line of the multiline here string ends with a new line – so that becomes the split point.

The array can be sorted by length of line. Ascending or descending wasn’t specified so here’s both options:

‘Sort by length ascending’
\$s | Sort-Object -Property Length

“`n ”
‘sort by length descending’
\$s | Sort-Object -Property Length -Descending

Removing the numbers to give justthe text and sorting by length of text. I trmmed the strings as some empty spaces had appeared in the arrays. I think because I copied the here-string

“`n ”
‘remove numbers sort by length ascending’
\$s.Trim() -replace ‘\d{1,2}\s’, ” | Sort-Object -Property Length #| group length | ft -a -wrap

“`n ”
‘remove numbers sort by length descending’
\$s.Trim() -replace ‘\d{1,2}\s’, ” | Sort-Object -Property Length -Descending

Create objects. Split on white space and restrict output to 2 elements – number and text in this case. Create object using New-object

“`n ”
#’create objects’
\$items = @()
\$s.Trim() | foreach {
\$item =  \$psitem -split ‘\s’,2
\$items += New-Object -TypeName PSObject -Property @{
Count = \$item[0] -as [int]
Item = \$item[1]
}
}

Count the number of birds

“`n ”
‘count of birds’
\$birdcount = (\$items -match ‘(Partridge|Doves|Hens|Birds|Geese|Swans)’ | Measure-Object -Property Count -Sum).Sum
\$birdcount

Count all items

“`n ”
‘count of items’
\$itemcount = (\$items | Measure-Object -Property Count -Sum).Sum
\$itemcount

If you treat the song as stating the gifts are cumulative then how many gifts are given in total.  Each item is given (13 – the day on which its given) times i.e. 12 to 1 times respectively.  The total number of items can be calculated like this

“`n ”
‘cumulative count of items’
\$total = 0
\$items | foreach {\$total += \$psitem.Count * (13-\$psitem.Count) }
\$total

As a bonus here’s how you calculate the cumulative number of each type of item.

“`n ”
‘cumulative number of each item’
\$totalitems =@()
\$items | foreach {
\$totalitems += New-Object -TypeName PSObject -Property @{
Count = \$psitem.Count * (13-\$psitem.Count)
Item = \$psitem.Item
}
}
\$totalitems

January 2, 2016  6:43 AM

## Happy New Year 2016

Profile: Richard Siddaway
Powershell

A new year and a number of things to which we can look forward.

The re-release of WMF 5.0. The WMF 5.0 download was pulled because a bug was over writing the module path. Look fot the download being available again soon.

Windows Server 2016 – Containers and Nano server give lots of new options for deployment and lots of new PowerShell to play with. There may even be other PowerShell changes – who knows given the new release processes.

In early April we have the PowerShell + DevOps Summit in Seattle. Late April sees the European PowerShell Conference in Hanover (tracks in German and English). Registration for both events is open.

The UK PowerShell group is reviving. After meetings in London and Manchester planning is underway for the next meetings – look for more info soon.

PowerShell in Action, third edition will appear.  Its already in early release and will complete this year.

A few other projects are in the pipeline which may or may not come to fruitition.

One prediction I can confidently make is that 2016 will NOT be the year that Unix/Linux conquers the desktop. 🙂

December 23, 2015  6:45 AM

## Objects, properties and values

Profile: Richard Siddaway
Powershell

One thing that seems to keep causing confusion is using Select-Object to pick off one or more properties from a set of objects:

PS> Get-CimInstance -ClassName Win32_Share | select Path

Path
—-
C:\WINDOWS
C:\

C:\windows\system32\spool\drivers
C:\Users

The gap in the output is because the IPC\$ share doesn’t have a path defined.

What you have is a ‘Selected’ version of the original object

PS> Get-CimInstance -ClassName Win32_Share | select Path | Get-Member

TypeName: Selected.Microsoft.Management.Infrastructure.CimInstance

Name        MemberType   Definition
—-        ———-   ———-
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Path        NoteProperty string Path=C:\WINDOWS

Very often you’ll only want the value of the property. In which case you need to use the –ExpandProperty parameter on Select-Object

PS> Get-CimInstance -ClassName Win32_Share | select -ExpandProperty Path
C:\WINDOWS
C:\

C:\windows\system32\spool\drivers
C:\Users

December 23, 2015  6:39 AM

## Infrastructure as Code article

Profile: Richard Siddaway
DevOps, Powershell

My Infrastructiure as Code article – part of an introducing DevOps series – has gone live http://ed-baker.com/devops-practices-infrastructure-as-code/

You can also link to it through http://blogs.technet.com/b/uktechnet/ where you’ll find the first in my series of article on PowerShell. Second one will be coming in the New Year

December 22, 2015  9:36 AM

## BinaryMiLog cmdlets

Profile: Richard Siddaway
CIM, Powershell, WMI

It’s not often I come across soemthing brand new in PowerShell but yesterday when I was investigating New-CimInstance I discovered 2 cmdlets in the CimCmdlets module I hadn’t noticed before. These are:

Export-BinaryMiLog

Import-BinaryMiLog

The cmdlets are used to export, or import, CIM instances as a binary encoded file.  Think of them as  Export-Clixml and Import-Clixml but for CIM instances.

Their usage is very simple:

Get-CimInstance -ClassName Win32_OperatingSystem |
Export-BinaryMiLog -Path testfile.bmil

This creates a   30 KB binary file – its definitely not human readable!

You don’t need to use a bmil extension (its the one in the help file) and you can use a CIM instance object instead of the pipeline

\$os = Get-CimInstance -ClassName Win32_OperatingSystem
Export-BinaryMiLog -InputObject \$os -Path testfile2.stuff

Getting the data back is performed by Import-BinaryMiLog

\$os1 = Import-BinaryMiLog -Path .\testfile.bmil
\$os2 = Import-BinaryMiLog -Path .\testfile2.stuff

The results appear to be a standard CIM object

Compare-Object -ReferenceObject \$os -DifferenceObject \$os1 -IncludeEqual
Compare-Object -ReferenceObject \$os -DifferenceObject \$os2 -IncludeEqual
Compare-Object -ReferenceObject \$os1 -DifferenceObject \$os2 –IncludeEqual

These cmdlets give you way to persist CIM objects to disk so that they can be referenced at a later date. If you need to test for changes to a system this could be a useful technique

December 21, 2015  3:36 PM

## New-CimInstance cmdlet and the–Key parameter

Profile: Richard Siddaway
CIM, Powershell, WMI

I was asked a question about the –Key parameter on New-CimInstance today. I wasn’t sure of the answer so I’ve done some experimentation.

I tend to avoid New-CimInstance if I can preferring to use the Create method on the CIM class – however not all CIM classes have a create method so need to fall back on New-CimInstance.

I started by looking at the documentation. The help file for New-CimInstance says:

##### -Key<String[]>

Specifies the properties that are used as keys. CimSession and ComputerName cannot be used when Key is specified.

That then leads to the question how do I discover the Key or Keys of a CIM class.  You can’t use the –Qualifier parameter in Get-CimClass because that works at the class level and Key is a property qualifier.  Means you need to use some code

function Get-CimClassKey {

param (

[string]\$CIMnamespace = ‘ROOT/cimv2’,

[string]\$CIMclass

)

\$class = Get-CimClass -Namespace \$CIMnamespace -ClassName \$CIMclass

foreach (\$property in \$class.CimClassProperties) {

\$property | Select-Object -ExpandProperty Qualifiers |
foreach {
if (\$_.Name -eq ‘key’){
\$property
}
}

}
}

The Key property of a class HAS to be given a value when a new instance of the class is created.

The New-CimInstance help file shows an example using Win32_Environment.  Adapring the example:

—-             ——–                                            ————-

Using our function to discover the Keys of Win32_Environment

PS> Get-CimClassKey -CIMclass Win32_Environment
Name               : Name
Value              :
CimType            : String
Flags              : Property, Key, NullValue
Qualifiers         : {read, key, MappingStrings, Override…}
ReferenceClassName :

Value              :
CimType            : String
Flags              : Property, Key, ReadOnly, NullValue
Qualifiers         : {key, MappingStrings, MaxLen, read}
ReferenceClassName :

—-             ——–                                            ————-

Using Win32_Environment you can use the Key parameter, or not, as long as you define values for the Name and Username properties.

Another example in the New-CimInstance help file uses the Win32_Process class.  The key for that class is the Handle property

PS> Get-CimClassKey -CIMclass Win32_process
Name               : Handle
Value              :
CimType            : String
Flags              : Property, Key, ReadOnly, NullValue
ReferenceClassName :

the Handle is appears to be identical to the ProcessId in value as far as I can determine

This now gets  messy:

Just the Handle.  BTW exmple 3 in the documentation has an error as Handle is a string not an integer

PS> New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′}
New-CimInstance : Provider is not capable of the attempted operation
At line:1 char:1
+ New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (Win32_Process:CimInstance) [New-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041024,Microsoft.Management.Infrastructure.CimCmdlets.NewCimInstanceCommand

PS> New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′} -Key Handle
New-CimInstance : Provider is not capable of the attempted operation
At line:1 char:1
+ New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′} -Key …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (Win32_Process (Handle = “0”):CimInstance) [New-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041024,Microsoft.Management.Infrastructure.CimCmdlets.NewCimInstanceCommand

The only way it works is if you use –ClientOnly to make an in memory CIM instance that only exists in your PowerShell session

PS> New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′} -Key Handle -ClientOnly

Handle PSComputerName
—— ————–
0

You can remove the –Key parameter

PS> New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′} -ClientOnly

Handle PSComputerName
—— ————–
0

Win32_Process has a Create method that takes these parameters

PS> \$class.CimClassMethods[‘Create’].Parameters

Name                       CimType Qualifiers                                 ReferenceClassName
—-                                 ——- ———-                                 ——————
CommandLine                 String {ID, In, MappingStrings}
CurrentDirectory            String {ID, In, MappingStrings}
ProcessStartupInformation Instance {EmbeddedInstance, ID, In, MappingStrings}
ProcessId                   UInt32 {ID, MappingStrings, Out}

Using Invoke-CimMethod

PS> Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine=’notepad.exe’}

ProcessId ReturnValue PSComputerName
——— ———– ————–
2648           0

Now trying New-CimInstance

PS> New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′; CommandLine=’notepad.exe’} -Key Handle
New-CimInstance : Provider is not capable of the attempted operation
At line:1 char:1
+ New-CimInstance -ClassName Win32_Process -Property @{Handle=’0′; Comm …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (Win32_Process (Handle = “0”):CimInstance) [New-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041024,Microsoft.Management.Infrastructure.CimCmdlets.NewCimInstanceCommand

Other variants of not including the Handle property and changing the handle value all fail with same error

Botton line is that New-CimInstance is a bit of a mess to use – with or without the –Key parameter (which doesn’t seem to do much).

If the CIM class has a create method Id recommend that you use that as a lot of CIm classes (or their providers) don’t work with New-cimInstance. In reality given that many of the CIM classes are effectively read only – you can’t create a new instance of Win32_ComputerSystem for example – it probably doesn’t matter.

December 21, 2015  5:41 AM

## JEA Helper Tool 2.0

Profile: Richard Siddaway
Powershell, Windows Server 2016

JEA – Just Enough Admin – is a security feature in WMF 5.0 and Windows Server 2016 (TP4) – providing RBAC for your Windows servers. You can allow people to perform the tasks needed by their role without giving them full access.

Doing all this manually can be a bit overwhelming. The JEA helper Tool can ease this work. Version 2.0 is know available for download – details from http://blogs.technet.com/b/privatecloud/archive/2015/12/20/introducing-the-updated-jea-helper-tool.aspx

December 20, 2015  9:10 AM

## Scripting Guy gets Pestered

Profile: Richard Siddaway
Powershell

The Scripting Guy blog has been running a series on Pester written by Dave Wyatt – the modules author.

Pester provides a way to perform, and automate, testing on your PowerShell code.

The series is:

http://blogs.technet.com/b/heyscriptingguy/archive/2015/12/14/what-is-pester-and-why-should-i-care.aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2015/12/15/getting-started-with-pester.aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2015/12/16/unit-testing-powershell-code-with-pester.aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2015/12/17/testing-script-modules-with-pester.aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2015/12/18/more-pester-feature-and-resources.aspx

December 20, 2015  9:00 AM

## New ScriptAnalyzer

Profile: Richard Siddaway
Powershell

A new version of Script Analyzer is available for download – http://blogs.msdn.com/b/powershell/archive/2015/12/17/scriptanalyzer-v1-2-0-released.aspx

A number of the rules have been updated and some new ones added