PowerShell for Windows Admins


January 16, 2012  2:43 PM

CIM sessions



Posted by: Richard Siddaway
PowerShell 3, WMI

When we last looked at the CIM cmdlets we saw that by default they use WSMAN to access remote computers but this only works if the remote computer is running PowerShell v3 with version 3.0 of the WSMAN stack.

We can force the CIM cmdlets to use DCOM by configuring a CIM session. These are analogous to PSsessions we create when using PowerShell remoting.

CIM sessions default to WSMAN – everything with CIM defaults to WSMAN unless you are accessing the local machine

PS> $sw = New-CimSession -ComputerName webr201
PS> $sw

Id           : 1
Name         : CimSession1
InstanceId   : 91ad5f5e-d5a9-4776-9965-3c520f8bb9a0
ComputerName : webr201
Protocol     : WSMAN

 

Get-CimInstance -CimSession $sw -ClassName Win32_ComputerSystem

 

Now returns the result over the session. Using a session or using

Get-CimInstance -ClassName Win32_ComputerSystem -computername webr201

 

both return an object of type

Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_ComputerSystem

 

So how do we create a session using DCOM?

 

PS> $opt = New-CimSessionOption -Protocol DCOM
PS> $sd = New-CimSession -ComputerName server02 -SessionOption $opt
PS> $sd

Id           : 2
Name         : CimSession2
InstanceId   : 3066aa29-7062-423d-a0ab-13b29cd86013
ComputerName : server02
Protocol     : DCOM

 

This session is used in the same way as a WSMAN session

Get-CimInstance -CimSession $sd -ClassName Win32_ComputerSystem

 

and returns the same object type.

We can even mix and match CIMsessions over WSMAN and DCOM

 

PS> Get-CimInstance -CimSession $sw, $sd -ClassName Win32_ComputerSystem | Format-Table Name, TotalPhysicalMemory –AutoSize

Name     TotalPhysicalMemory
—-     ——————-
SERVER02         17108066304
WEBR201            536403968

 

The CimSession parameter takes pipeline input so we can do this

Get-CimSession | Get-CimInstance -ClassName Win32_ComputerSystem | Format-Table Name, TotalPhysicalMemory –AutoSize

 

which has to be a cool way to access remote machines.

January 15, 2012  3:43 PM

Boot partition



Posted by: Richard Siddaway
Disks, PowerShell v2, WMI

Do you know which disk partition your system boots from?

Its easy to find out

function get-bootpartition {            
[CmdletBinding()]            
param (            
 [parameter(ValueFromPipeline=$true,            
   ValueFromPipelineByPropertyName=$true)]            
 [string]$computername="$env:COMPUTERNAME"            
)            
PROCESS{                
              
  Get-WmiObject -Class Win32_DiskPartition -Filter "BootPartition = $true" -ComputerName $computername            
              
}            
}

 

The filter only returns the partition where BootPartition is set to True


January 14, 2012  12:44 PM

CIM cmdlets and remote machines



Posted by: Richard Siddaway
PowerShell 3, WMI

To access a remote machine using WMI we use

Get-WmiObject -Class Win32_ComputerSystem -ComputerName webr201

 

This is replicated using the CIM cmdlets
Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName webr201

 

No lets repeat with another server
Get-WmiObject  -Class Win32_ComputerSystem -ComputerName server02

and with CIM
Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName server02

Get-CimInstance : The WS-Management service cannot process the request. A DMTF resource URI was used to access a
non-DMTF class. Try again using a non-DMTF resource URI.
At line:1 char:1
+ Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName server02
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Win7Test.Manticore.org:) [Get-CimInstance], CimException
    + FullyQualifiedErrorId : 2150859065,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand

 

We get an error.  Huh! What’s going on?

The problem is that the WMI cmdlets use DCOM to access remote machines. By default the CIM cmdlets use WSMAN. In fact the only time they use DCOM is to access the local machine IF a machine name such as “.”, “localhost” or “$env:COMPUTERNAME” isn’t used i.e. no use of the –Computername parameter to access local machines.

My webr201 server is using PowerShell v3 but server02 is still on PowerShell v2. We can see the difference

PS> Test-WSMan -ComputerName webr201 -Authentication default

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 6.1.7601 SP: 1.0 Stack: 3.0

 

PS> Test-WSMan -ComputerName server02 -Authentication default

wsmid           : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor   : Microsoft Corporation
ProductVersion  : OS: 6.1.7601 SP: 1.0 Stack: 2.0

 

Webr201 is using WSMAN 3 from PowerShell v3 so it works with the CIM cmdlets but server02 is using WSMAN 2 so doesn’t work.   Does that mean that we can’t use the CIM cmdlets against systems running PowerShell v2? NO it doesn’t – it means we need to use CIM sessions but that is a topic for next time


January 12, 2012  3:25 PM

Friday 13th



Posted by: Richard Siddaway
Books

Tomorrow is Friday 13th and Manning are offering $13 off any purchase at manning.com.

This would be a good time to get a copy of PowerShell in Practice or PowerShell and WMI

use code “fri1312” at checkout


January 9, 2012  2:15 PM

CIM instances



Posted by: Richard Siddaway
PowerShell 3, Windows 8, WMI

We are use to using Get-WmiObject to retrieve information from WMI. if you have been following this blog for any length of time you will have see lots of examples of that particular cmdlet. The CIM equivalent is Get-CIMInstance. It might appear that Get-CIMClass would be used but that is used to get information about the WMI class itself. think Get-WmiObject –List  on steroids.

This should be familiar

Get-WmiObject -Class Win32_ComputerSystem

The direct comparison is

Get-CimInstance -ClassName Win32_ComputerSystem

 

We can run WQL queries

$q = "SELECT * FROM Win32_ComputerSystem"
Get-WmiObject -Query $q

 

Get-CimInstance -Query $q

 

And we can filter

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3"

Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"

 

Another difference is that CIM cmdlets tend to default to a table output but WMI cmdlets tend to default to a list

 

We can even select properties

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -Property DeviceID, FreeSpace, Size

Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3" -SelectProperties DeviceID, FreeSpace, Size

 

Here we get a big difference

WMI returns the properties we asked for plus the System properties (those starting with __) for the class. CIM returns the whole object but only the select properties and the system type properties are populated.

 

So far you could be forgiven for thinking these are very similar and we don’t need both. The big differences come when we look at access remote machines next time.


January 6, 2012  2:39 PM

WMI and CIM



Posted by: Richard Siddaway
PowerShell 3, Windows 8, WMI

Do you know the difference between WMI and CIM?

CIM is the Common Information Model – http://www.dmtf.org/standards/cim

“CIM provides a common definition of management information for systems, networks, applications and services, and allows for vendor extensions. CIM’s common definitions enable vendors to exchange semantically rich management information between systems throughout the network.”

 

WMI is Microsoft’s implementation of CIM

Get-WmiObject CIM_DiskDrive
Get-WmiObject Win32_DiskDrive

return the same information

Win32_DiskDrive is derived from CIM_DiskDrive.  The CIM class is the superclass for the Win32 class.

Why is this important?

Because in PowerShell v3 Microsoft introduce a while new API for working with WMI -  and whole new bunch of cmdlets

Get-CimAssociatedInstance
Get-CimClass
Get-CimInstance
Get-CimSession
Invoke-CimMethod
New-CimInstance
New-CimSession
New-CimSessionOption
Register-CimIndicationEvent
Remove-CimInstance
Remove-CimSession
Set-CimInstance

compare these to the WMI cmdlets

Get-WmiObject
Invoke-WmiMethod
Register-WmiEvent
Remove-WmiObject
Set-WmiInstance

The analogous CIM cmdlets are highlighted.

The CIM cmdlets use different .NET classes to WMI cmdlets

PS> Get-WmiObject Win32_DiskDrive | gm

   TypeName: System.Management.ManagementObject#root\cimv2\Win32_DiskDrive

 

PS> Get-CimInstance Win32_DiskDrive | gm

   TypeName: Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DiskDrive

 

Microsoft have made a big investment in WMI/CIM for Windows 8.  I’ll explore some of the new things in coming posts


January 2, 2012  8:35 AM

UK PowerShell Group–January 2012



Posted by: Richard Siddaway
PowerShell, User Group

This is our five year anniversary meeting!!

So it seems fitting to look at PowerShell v3 and how we got to where we are now.


When: Tuesday, Jan 24, 2012 7:30 PM (GMT)


Where: Virtual

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

A look at whats new in PowerShell v3 and how we can incorporate it into our administration tasks

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: SHGTW9
    Entry Code: 3%8>`{p’K
    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.


January 1, 2012  7:50 AM

UK PowerShell Group – Q1 2012



Posted by: Richard Siddaway
PowerShell, User Group

The first three meetings for 2012 are

 

27 March 2012             -  CIM cmdlets & cmdlets over objects 

       
28 February 2012        -  PowerShell and SQL Server

 

24 January 2012           -  PowerShell v3 overview

 

Details to follow


January 1, 2012  6:12 AM

Changing IP Connection Metric



Posted by: Richard Siddaway
Network, PowerShell, WMI

A question on the forums asked how the connection metrics could be set on a Windows system.

We need to start by identifying the network adapters using this function

function test-ipmetric {
Get-WmiObject -Class Win32_NetworkAdapter -Filter "AdapterType = ‘Ethernet 802.3′" |
foreach {
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=$($_.DeviceId)" |
select Description, Index, IPEnabled, IPConnectionMetric
}
}

test-ipmetric | ft -a

Description                                                                                  Index IPEnabled IPConnect
                                                                                                                               ionMetric
———–                                                                                      —–     ———    ———
NVIDIA nForce 10/100/1000 Mbps Networking Controller              7         True        20
Atheros AR5007 802.11b/g WiFi Adapter                                      11        True        10
Microsoft Virtual WiFi Miniport Adapter                                          17        False

 

I get three adapters returned

The important ones are those that have IPEnabled set to True.

identify which is to have priority then run

function set-ipmetric {
param (
[int]$index,
[int]$metric
)
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "Index=$index" |
Invoke-WmiMethod -Name SetIPConnectionMetric -ArgumentList $metric
}

I used

set-ipmetric -index 7 -metric 200

set-ipmetric -index 11 -metric 100

This sets my wired to a higher metric than the wireless. If I wanted it the other way round

set-ipmetric -index 7 -metric 100

set-ipmetric -index 11 -metric 200

The system must be rebooted for the changes to take effect


December 23, 2011  1:34 PM

Selecting Property order



Posted by: Richard Siddaway
PowerShell v2

If you run

Get-WmiObject -Class Win32_ComputerSystem

you get a few properties displayed

Domain              : WORKGROUP
Manufacturer        : Hewlett-Packard
Model               : HP G60 Notebook PC
Name                : RSLAPTOP01
PrimaryOwnerName    : Richard
TotalPhysicalMemory : 2951139328

 

Now if you want all properties you need

Get-WmiObject -Class Win32_ComputerSystem | fl *

or

Get-WmiObject -Class Win32_ComputerSystem | select *

If you want a particular set of properties then this will work

Get-WmiObject -Class Win32_ComputerSystem | select Name, SystemType, Manufacturer, Model, BootupState

 

A comment was left on this post

http://msmvps.com/blogs/richardsiddaway/archive/2011/12/23/1792823.aspx

regarding how the reader wanted a specific set of properties displayed first and then all of the other properties in any appropriate order

You might think that this would work

Get-WmiObject -Class Win32_ComputerSystem | select Name, SystemType, Manufacturer, Model, BootupState, *

but in fact we get a series of errors and then all of the properties in the standard order.

Select-Object has  –Property and –ExcludeProperty parameters but they won’t help us as we want to display all properties

One thing to remember is that you can do this

$p = "Name", "SystemType", "Manufacturer", "Model", "BootupState"
Get-WmiObject -Class Win32_ComputerSystem | select $p

 

Define the list of properties in an array and use that as the selection.  This because –Property is a positional property and takes position 1 so is assumed if no parameter name is supplied. What we are doing is this

$p = "Name", "SystemType", "Manufacturer", "Model", "BootupState"
Get-WmiObject -Class Win32_ComputerSystem | select -Property $p

This enables us to write a function that takes an object and list of properties as input and creates a selection list based on the object’s full property list. The properties defined to the function are selected first and then all other properties in the order that Get-Member supplies them.

function Select-Order {            
[CmdletBinding()]            
param (            
[parameter(Position=0,            
   ValueFromPipeline=$true)]            
   $InputObject,             
[string[]]$firstprop            
)            
            
PROCESS {            
$proplist = $firstprop            
            
$Inputobject | Get-Member -MemberType Property |            
foreach {            
 if ($firstprop -notcontains $_.Name){            
   $proplist += $_.Name            
 }            
}            
            
$InputObject | select -Property $proplist            
}}

 

You can use it like this

$p = "Name", "SystemType", "Manufacturer", "Model", "BootupState"

Get-WmiObject Win32_ComputerSystem | Select-Order -firstprop $p

or

Get-WmiObject Win32_ComputerSystem | Select-Order -firstprop "Name", "SystemType", "Manufacturer", "Model", "BootupState"

or

$o = Get-WmiObject Win32_ComputerSystem                                   
Select-Order -InputObject $o -firstprop $p 

or

Select-Order -InputObject $o -firstprop "Name", "SystemType", "Manufacturer", "Model", "BootupState"


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: