Monthly Archive

Categories

Monthly Archives: March 2014

Continue please

I needed to be able to skip processing in a loop and remembered that the continue command suspends the loop processing and immediate goes back to the top of the loop. I thought a quick look at how it works in different types of loop would be worthwhile.

These all work and produce the same output

1

2

3

5

6

 

FOR loop

for ($i=1; $i -le 6; $i++){
  if ($i -eq 4) {continue}
  $i
}

 

WHILE loop

$i = 0
while ($i -lt 6){
$i++
if ($i -eq 4) {continue}
$i
}

 

DO loop

$i = 0
do {
$i++
if ($i -eq 4) {continue}
$i
} while ($i -lt 6)

 

$i = 0
do {
$i++
if ($i -eq 4) {continue}
$i
} until ($i -ge 6)

 

FOREACH loop

$numbers = 1..6
foreach ($number in $numbers) {
if ($number -eq 4) {continue}
$number
}

 

THIS NEXT ONE WON’T WORK

1..6 |
foreach {
if ($psitem -eq 4) {continue}
$psitem
}

 

You will terminate the pipeline by using continue.

One way to do this would be:

1..6 |
foreach {
if ($psitem -ne 4) {$psitem}
}

 

Continue is a useful trick that gives you more control within the loop

WMI type accelerators

Something you don’t see used very often but that you need to be aware of are the WMI type accelerators. These were introduced as part of PowerShell 1.0 and have continued to be available in later versions. 

A type accelerator is a shortcut to using a .NET class – remember everything in PowerShell is >NET based – even WMI.  There are three accelerators:

[wmi]

[wmi]"root\cimv2:Win32_Process.Handle='5028'"

This is the same as

Get-WmiObject -Class Win32_Process -Filter "Handle=5028"

or

Get-CimInstance -ClassName Win32_Process -Filter "Handle=5028"

The draw back is that you have to use the WMI class Key which is Handle in Win32_Process. Get-WmiObject and Get-CimInstance give you a wider set of filtering options – the –Filter parameter will work on most properties

[wmiclass]

This provides a shortcut for creating new instances:

$p = [wmiclass]'Win32_Process'
$p.Create("calc.exe")

This was your only option in PowerShell 1.0 for accessing the Create method. With PowerShell 2.0 and 3.0 these options were added respectively:

Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList 'calc.exe'

Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='calc.exe'}

[wmisearcher]

The final WMI type accelerator can be used to find WMI data. You need to use a WQL query

$query = [wmisearcher]"SELECT * FROM Win32_Process WHERE Name='calc.exe'"
$query.Get()

Your alternatives are:

Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='calc.exe'"

Get-CimInstance -Query "SELECT * FROM Win32_Process WHERE Name='calc.exe'"

OR better still

Get-WmiObject -Class Win32_Process -Filter "Name='calc.exe'"

Get-CimInstance -ClassName Win32_Process -Filter "Name='calc.exe'"

Lots of choices and one of these techniques will solve your problem when working with WMI.  More information is available in Chapter 3 of PowerShell and WMI – www.manning/siddaway2

Multiple book offers

There are multiple money off offers from Manning for you to consider.

Firstly – tomorrow March 18 2014: Half off Learn Active Directory Management in a Month of Lunches. Use code dotd031814au at www.manning.com/siddaway3/

The deal will go live at Midnight US ET and will stay active for ~48 hours.

Some other books in the Month of Lunches series will also be available under this offer.

Secondly – PowerShell in Depth 2E is going on to Early Access - http://www.manning.com/jones6/ You can get 50% off using code -  pid2eco

It is valid for the MEAP, eBook and pBook.  The code will be active until March 20.

Yes, we updated PowerShell in Depth for PowerShell v4.  Every chapter has been examined and brought up to date with v4 material added as appropriate. We have also added chapters including one on Desired State Configuration.

  Thirdly there is a 45% of everything offer! Just enter wm031714 in the Promotional Code box when you check out. Offer applies to your entire purchase--eBook, pBook, or MEAP. Expires March 25.

  Now would be a good time to get those books you’ve promising yourself

Select is a filter

This is a common scenario:

Get-WmiObject -Class Win32_Logicaldisk | select Name, Size, Freespace

You will see a display with three properties – turning them into a list for ease of display:

Name      : C:
Size      : 248951861248
Freespace : 171627724800

What this means is that you’ve got an object with 3 properties.

£> Get-WmiObject -Class Win32_Logicaldisk | select Name, Size, Freespace | Get-Member

   TypeName: Selected.System.Management.ManagementObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
Freespace   NoteProperty System.UInt64 Freespace=171627569152
Name        NoteProperty System.String Name=C:
Size        NoteProperty System.UInt64 Size=248951861248

The object type changes – its now a Selected.System.Management.ManagementObject rather than System.Management.ManagementObject#root\cimv2\Win32_LogicalDisk you get from WMI.

Try this to see the whole list of properties

Get-WmiObject -Class Win32_Logicaldisk | Get-Member

Select-Object is great because you can trim down the size of the objects on your pipeline but you have to remember that once you performed that selection its a one way street you can’t get back to the original.

If you need to perform multiple actions on the objects put them into a variable:

$disks = Get-WmiObject -Class Win32_Logicaldisk

then you can do:

$disks | <pipeline 1>

$disks | <pipeline 2>

or

foreach ($disk in $disks) { <do stuff to the disks>}

Where and when to filter you data using Where-Object or Select-Object is part of your design process and only you know what works in your situation. The rule of thumb is filter early to reduce the data on the pipeline but knowing when to break that rule is what makes or breaks your solution

Learn Active Directory Management in a MoL on offer

Learn Active Directory Management in a MoL is 43% off through April 3, 2014 with code pbradm at www.manning.com/siddaway3/

Module confusion–what’s really in PowerShell 3 and 4

If I run

Get-Module –ListAvailable

on my Windows 8.1 system (PowerShell 4.0) I find a total of 58 modules installed in $pshome\modules i.e. C:\windows\system32\WindowsPowerShell\v1.0\Modules

These are the modules installed as part of PowerShell. Right?

Wrong?

Compare this with a Windows 7 machine that’s been upgraded to PowerShell 4.0.  Repeating the exercise I find a grand total of 15 modules.

So where has the other 75% of my functionality gone. 

This is the breakdown down of the modules installed on the Windows 7 machine  - terminology is mine (feel free to disagree with the groupings).

Core PowerShell:

Microsoft.PowerShell.Diagnostic
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
CimCmdlets
ISE
Microsoft.WSMan.Management

File Transfer module

BitsTransfer

Troubleshooting:

PSDiagnostics
TroubleshootingPack

Other related engines:

PSDesiredStateConfiguration
PSScheduledJob
PSWorkflow
PSWorkflowUtility

and that’s it. Everything else as far as I can determine is CDXML based and therefore can’t be made available on legacy systems. The following modules are included in that category:

AppBackgroundTask
AppLocker
Appx
AssignedAccess
BitLocker
BranchCache
Defender
DirectAccessClientComponents
Dism
DnsClient
International
iSCSI
Kds
MMAgent
MsDtc
NetAdapter
NetConnection
NetEventPacketCapture
NetLbfo
NetNat
NetQos
NetSecurity
NetSwitchTeam
NetTCPIP
NetWNV
NetworkConnectivityStatus
NetworkTransition
PcsvDevice
PKI
PrintManagement
ScheduledTasks
SecureBoot
SmbShare
SmbWitness
StartScreen
Storage
TLS
TrustedPlatformModule
VpnClient
Wdac
WindowsDeveloperLicense
WindowsErrorReporting
WindowsSearch

A CDXML based module is produced by taking a CIM (WMI) class and wrapping it in some simple XML and saving it as a .cdxml file. This can then be published as a PowerShell module. The CIM classes won’t be made available on downlevel systems so you won’t find this functionality on anything earlier than Windows 8/2012.

If you need the functionality supplied by these modules you will either have to use the old command line tools or a WMI class – much of the functionality of the NetAdapter and NETCPIP modules for instance can be duplicated using Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration..

AD Management in a Month of Lunches in print

Manning have released the print edition of Learn Active Directory Management in a Month of Lunches - http://www.manning.com/siddaway3/ – joining the pdf version released earlier.  ePub & Kindle versions scheduled for 20 March

Get-ADUser issue fixed with hotfix

The issue that I discussed in these posts:

http://richardspowershellblog.wordpress.com/2013/11/08/get-aduser-issue-2/

http://richardspowershellblog.wordpress.com/2013/11/06/get-aduser-issue/

With Get-ADUser and –Properties * in a forest level below 2012 R2 has been resolved  in this update:

http://support.microsoft.com/kb/2923122

End of PowerShell Jobs week

My series on PowerShell Jobs for the Scripting Guy blog has finished.  The set of articles is:

Jobs week 1 : Introduction to PowerShell jobs
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/02/powershell-jobs-week-introduction-to-powershell-jobs.aspx 
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/02/powertip-control-job-starts-with-powershell.aspx

Jobs week 2 : WMi and CIM jobs
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/03/powershell-jobs-week-wmi-and-cim-jobs.aspx 
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/03/powertip-use-powershell-to-keep-job-data.aspx 

Jobs week 3 : Remote Jobs
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/04/powershell-jobs-week-remote-jobs.aspx 
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/04/powertip-use-powershell-to-find-job-help.aspx 

Jobs week 4 : Scheduled Jobs
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/05/powershell-jobs-week-scheduled-jobs.aspx 
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/05/powertip-use-powershell-to-discover-tasks-associated-with-scheduled-jobs.aspx 

Jobs week 5 : Workflow Jobs
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/06/powershell-jobs-week-jobs-and-workflows.aspx 
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/06/powertip-stop-a-powershell-job.aspx 

Jobs week 6 : Job processes
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/07/powershell-jobs-week-job-processes.aspx
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/07/powertip-protect-the-data-produced-by-powershell-jobs.aspx

Jobs week 7 : Jobs in the enterprise
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/08/powershell-jobs-week-jobs-in-the-enterprise.aspx
http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/08/powertip-find-more-information-about-windows-powershell-jobs.aspx 

 

Enjoy

PowerShell Summit 2014 edging even closer

Now we’re in March the Summit is getting closer.  Looking forward to see friends old & new and listening to some excellent sessions.

If you haven’t registered there’s still places available.

As a bonus one of the things you’ll take away is a module for working with the registry – filling one of gaps in the PowerShell cmdlets for Windows administrators