PowerShell for Windows Admins


January 1, 2012  7:50 AM

UK PowerShell Group – Q1 2012

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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"


December 23, 2011  7:48 AM

PowerShell workflows

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Just as remoting was viewed as the biggest gain in PowerShell v2 it looks like PowerShell workflows will be one of the biggest features on PowerShell v3.

Some examples and explanation are available from http://blogs.msdn.com/b/powershell/archive/2011/12/22/another-holiday-gift-from-the-powershell-team-powershell-3-0-ctp2-getting-started-with-windows-powershell-workflow.aspx

Enjoy


December 20, 2011  1:54 PM

Recordings, Slides and Demo scripts

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Here are the recordings, slides and demo scripts from last weeks two Live Meetings.

Introduction to WMI

https://skydrive.live.com/?cid=43cfa46a74cf3e96#cid=43CFA46A74CF3E96&id=43CFA46A74CF3E96%212931

 

WSMAN, WMI and CIM

https://skydrive.live.com/?cid=43cfa46a74cf3e96#cid=43CFA46A74CF3E96&id=43CFA46A74CF3E96%212933

 

Down load and unzip to find all items


December 12, 2011  3:51 PM

WMI LIKEs Wildcards

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

You may hear or read that WMI can’t accept wildcards. WRONG

WMI accepts wildcards but not the ones you might expect.

 

Consider

Get-Process p*

This gets all the process that begin with the letter p

To do something similar with WMI we need to use the –Filter parameter. We can get a single process like this

Get-WmiObject -Class Win32_Process -Filter "Name=’powershell.exe’"

so you may want to try this

Get-WmiObject -Class Win32_Process -Filter "Name=’p*’"

 

Oops no returns of any kind.

That’s because in the filter we are using WQL which uses the SQL wildcards

% = *   multiple characters

_ = ?    single character

 

OK then this will work

Get-WmiObject -Class Win32_Process -Filter "Name=’p%’"

 

Oh no it won’t because a further complication is that we have to use the WQL LIKE operator not =

Get-WmiObject -Class Win32_Process -Filter "Name LIKE ‘p%’"

And we have a winner

 

To use the single character wildcard (which in my experience doesn’t get used as much as the multi-character)

Get-WmiObject -Class Win32_Process -Filter "Name LIKE ‘powershell.e_e’"

 

And as an added bonus the title of the post give us a way to remember to use the LIKE operator.


December 11, 2011  2:32 PM

International WMI week

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

As far as I am concerned this is International WMI week.  I am delivering a Live Meeting session to the Corpus Christi (Texas) PowerShell group on Tuesday – An Introduction to WMI & PowerShell then on Thursday I am delivering a session to the UK PowerShell group http://msmvps.com/blogs/richardsiddaway/archive/2011/12/04/uk-powershell-group-december-2011.aspx – talking about WMI. WSMAN and the new CIM cmdlets in PowerShell v3

Hopefully both events will be recorded. I post the links to the recordings after the events.


December 11, 2011  3:57 AM

Happy Birthday PowerShell

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

With all the things happening in the last month – including the release of PowerShell v3 CTP 2 – one thing that seems to have been missed is that PowerShell is 5 years old!

Yes – its just over 5 years since the release of PowerShell v1 was announced in Barcelona at the IT Forum http://blogs.msdn.com/b/powershell/archive/2006/11/14/windows-powershell-1-0-released.aspx

We have come an awful long way in those five years:

  • a thriving, passionate and growing PowerShell community – the creation of the first PowerShell User Group was also announced in November 2006 in Barcelona. The UK group will have its fifth anniversary meeting next month!
  • PowerShell v2 released with remoting, WSMAN, jobs, transactions and increased WMI support, ISE, Modules etc
  • PowerShell v3 in CTP with workflow, CIM, cmdlets over objects, automatic module import, updatable help etc
  • PowerShell support is built into the major Microsoft products
  • third party support is growing – Quest, VMware, Citrix etc etc

PowerShell has gone from a “what’s that” technology to an “I’m going to have to learn that” technology. We still have a long way to go before is thought of as the tool of choice by the bulk of IT pros but we are heading in the right direction.

The next five years are going to be fun.


December 10, 2011  9:54 AM

WMI, WSMAN, CIM and Authentication pt II

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Last time we saw that the WMI cmdlets have an Authentication parameter that uses DCOM authentication. It is possible to ignore this Authentication need if the WSMAN or CIM (PS v3 CTP 2) cmdlets are used.

If you look at the WSMAN cmdlets then the following cmdlets have an Authentication parameter in PS v2

Test-WSMan
Get-WSManInstance
Set-WSManInstance
Invoke-WSManAction
Connect-WSMan

 

These two cmdlets have an Authentication parameter though it appears as AuthenticationMechanism to the help files.
New-WSManInstance
Remove-WSManInstance

 

In PSv3 CTP 2 all of them have an Authentication parameter

For the new CIM cmdlets the following  has an authentication parameter

New-CimSession

 

New-CimSession is analagous to New-PSsession for remoting in that it creates a session to a remote system over WSMAN or DCOM

 

These authentication parameters are totally different to the WMI Authentication parameter.

 

From the help file

   -Authentication <Authentication>

Specifies the authentication mechanism to be used at the server. Possible values are:

- Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.
- Default : Use the authentication method implemented by the WS-Management protocol. This is the default.
- Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.
- Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates.
- Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the  scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.
- CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate  credentials. This option is designed for commands that run on one remote computer but collect data from or run  additional commands on other remote computers.

Caution: CredSSP delegates the user’s credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are  passed to it, the credentials can be used to control the network session.

This Authentication follows the network protocols and is used with the Credential parameter to determine Authentication & Authorisation for the resources that are requested.

In a domain setting it is most probable that you will not need to worry about these parameters as your user account should have the required level of access otherwise why are you attempting this action?

In a non-domain situation the WSMAN cmdlets can set the credential & authentication on individual connections (if required) but CIM can only do it at the session level.  Is this a problem?

Probably not as we can set these in a Cim session that can encompass all of the systems we need to access. The time this wouldn’t work is if all of the machines required different credentials – that would get messy but then is that poor administration to get into that position?


December 10, 2011  6:26 AM

WMI, WSMAN, CIM and Authentication

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Authentication parameters in WMI, WSMAN and the new CIM cmdlets can be confusing.

The PowerShell WMI cmdlets have an Authentication parameter that uses DCOM authentication. Using the Authentication parameter with the WMI cmdlets was explained here
http://msmvps.com/blogs/richardsiddaway/archive/2011/08/04/authentication-impersonation-and-privileges.aspx

 

This is not present on the WSMAN cmdlets (in PowerShell v2 and v3 CTP 2) and the new CIM cmdlets (in PowerShell v3 CTP 2)

 

The Authentication parameter is not required on the WSMAN and CIM cmdlets as it provides DCOM authentication. WSMAN bypasses DCOM and by default the CIM cmdlets use WSMAN to access remote machines.

 

The following tests are all run in a Windows 2008 R2 domain.

We will use the IIS WMI provider because it explicitly requires Packet Privacy for remote access

Target is Microsoft Windows Web Server 2008 R2 SP 1.  PS Remoting is emabled to ensure WSMAN configured.
PowerShell v2 is installed.

Running locally on the target
Get-WmiObject -Namespace ‘root\webadministration’ -Class Site

works as we would expect

############################################################################################
Running the same command from a different machine:
Windows 2008 R2 SP 1 with PowerShell v2.  This machine is a domain controller

PS> Get-WmiObject -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201
Get-WmiObject : Access denied
At line:1 char:14
+ Get-WmiObject <<<<  -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

PS> Get-WmiObject -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201 -Authentication 6

__GENUS                    : 2
__CLASS                    : Site
__SUPERCLASS               : ConfiguredObject
__DYNASTY                  : Object
__RELPATH                  : Site.Name="Default Web Site"
__PROPERTY_COUNT           : 10
__DERIVATION               : {ConfiguredObject, Object}
__SERVER                   : WEBR201
__NAMESPACE                : root\webadministration
__PATH                     : \\WEBR201\root\webadministration:Site.Name="Default Web Site"
ApplicationDefaults        : System.Management.ManagementBaseObject
Bindings                   : {System.Management.ManagementBaseObject}
FtpServer                  : System.Management.ManagementBaseObject
Id                         : 1
Limits                     : System.Management.ManagementBaseObject
LogFile                    : System.Management.ManagementBaseObject
Name                       : Default Web Site
ServerAutoStart            : True
TraceFailedRequestsLogging : System.Management.ManagementBaseObject
VirtualDirectoryDefaults   : System.Management.ManagementBaseObject

Notice we need the -Authentication 6 (enables Packet Privacy DCOM authentication)

using the WSMAN cmdlets

PS> $uri = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/webadministration/*"
PS> $filter = "SELECT * FROM Site"
PS> Get-WSManInstance -ResourceURI $uri -Enumerate -Dialect WQL -Filter $filter -ComputerName webr201

xsi                        : http://www.w3.org/2001/XMLSchema-instance
p                          : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/webadministration/Site
cim                        : http://schemas.dmtf.org/wbem/wscim/1/common
type                       : p:Site_Type
lang                       : en-US
ApplicationDefaults        : ApplicationDefaults
Bindings                   : Bindings
FtpServer                  : FtpServer
Id                         : 1
Limits                     : Limits
LogFile                    : LogFile
Name                       : Default Web Site
ServerAutoStart            : true
TraceFailedRequestsLogging : TraceFailedRequestsLogging
VirtualDirectoryDefaults   : VirtualDirectoryDefaults

Notice that we don’t have to use an -Authentication parameter because we are not using DCOM

##########################################################################################
Repeat test on non domain controller
Windows 7 SP 1 PowerShell 2

PS> Get-WmiObject -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201
Get-WmiObject : Access denied
At line:1 char:14
+ Get-WmiObject <<<<  -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

PS> Get-WmiObject -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201 -Authentication 6

__GENUS                    : 2
__CLASS                    : Site
__SUPERCLASS               : ConfiguredObject
__DYNASTY                  : Object
__RELPATH                  : Site.Name="Default Web Site"
__PROPERTY_COUNT           : 10
__DERIVATION               : {ConfiguredObject, Object}
__SERVER                   : WEBR201
__NAMESPACE                : root\webadministration
__PATH                     : \\WEBR201\root\webadministration:Site.Name="Default Web Site"
ApplicationDefaults        : System.Management.ManagementBaseObject
Bindings                   : {System.Management.ManagementBaseObject}
FtpServer                  : System.Management.ManagementBaseObject
Id                         : 1
Limits                     : System.Management.ManagementBaseObject
LogFile                    : System.Management.ManagementBaseObject
Name                       : Default Web Site
ServerAutoStart            : True
TraceFailedRequestsLogging : System.Management.ManagementBaseObject
VirtualDirectoryDefaults   : System.Management.ManagementBaseObject

Now WSMAN

PS> $uri = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/webadministration/*"
PS> $filter = "SELECT * FROM Site"
PS> Get-WSManInstance -ResourceURI $uri -Enumerate -Dialect WQL -Filter $filter -ComputerName webr201

xsi                        : http://www.w3.org/2001/XMLSchema-instance
p                          : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/webadministration/Site
cim                        : http://schemas.dmtf.org/wbem/wscim/1/common
type                       : p:Site_Type
lang                       : en-US
ApplicationDefaults        : ApplicationDefaults
Bindings                   : Bindings
FtpServer                  : FtpServer
Id                         : 1
Limits                     : Limits
LogFile                    : LogFile
Name                       : Default Web Site
ServerAutoStart            : true
TraceFailedRequestsLogging : TraceFailedRequestsLogging
VirtualDirectoryDefaults   : VirtualDirectoryDefaults

#############################################################################################
Repeat on Windows 7 SP 1 running PowerShell v3 CTP 2

PS> Get-WmiObject -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201
Get-WmiObject : Access denied
At line:1 char:1
+ Get-WmiObject -Namespace ‘root\webadministration’ -Class Site -ComputerName webr …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

PS> Get-WmiObject -Namespace ‘root\webadministration’ -Class Site -ComputerName webr201 -Authentication 6

__GENUS                    : 2
__CLASS                    : Site
__SUPERCLASS               : ConfiguredObject
__DYNASTY                  : Object
__RELPATH                  : Site.Name="Default Web Site"
__PROPERTY_COUNT           : 10
__DERIVATION               : {ConfiguredObject, Object}
__SERVER                   : WEBR201
__NAMESPACE                : root\webadministration
__PATH                     : \\WEBR201\root\webadministration:Site.Name="Default Web Site"
ApplicationDefaults        : System.Management.ManagementBaseObject
Bindings                   : {System.Management.ManagementBaseObject}
FtpServer                  : System.Management.ManagementBaseObject
Id                         : 1
Limits                     : System.Management.ManagementBaseObject
LogFile                    : System.Management.ManagementBaseObject
Name                       : Default Web Site
ServerAutoStart            : True
TraceFailedRequestsLogging : System.Management.ManagementBaseObject
VirtualDirectoryDefaults   : System.Management.ManagementBaseObject
PSComputerName             : WEBR201

Now repeat the WSMAN test
PS> $uri = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/webadministration/*"
PS> $filter = "SELECT * FROM Site"
PS> Get-WSManInstance -ResourceURI $uri -Enumerate -Dialect WQL -Filter $filter -ComputerName webr201

xsi                        : http://www.w3.org/2001/XMLSchema-instance
p                          : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/webadministration/Site
cim                        : http://schemas.dmtf.org/wbem/wscim/1/common
type                       : p:Site_Type
lang                       : en-US
ApplicationDefaults        : ApplicationDefaults
Bindings                   : Bindings
FtpServer                  : FtpServer
Id                         : 1
Limits                     : Limits
LogFile                    : LogFile
Name                       : Default Web Site
ServerAutoStart            : true
TraceFailedRequestsLogging : TraceFailedRequestsLogging
VirtualDirectoryDefaults   : VirtualDirectoryDefaults

#############################################################################################
Now we look at the CIM cmdlets. They use WSMAN by default as the remote access mechanism
Windows 7 SP 1 with PowerShell v3 CTP 2

PS> Get-CimInstance -ClassName site -Namespace ‘root/webadministration’ -ComputerName Webr201
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 site -Namespace ‘root/webadministration’ -ComputerNam …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Win7Test.Manticore.org:) [Get-CimInstance], CimException
    + FullyQualifiedErrorId : 2150859065,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand

Now lets install PowerShell v3 CTP 2 on the remote machine and repeat. Remember that .NET 4 is required for PowerShell v3

PS> Get-CimInstance -ClassName site -Namespace ‘root/webadministration’ -ComputerName Webr201

ApplicationDefaults        : ApplicationElementDefaults
Bindings                   : {BindingElement (Protocol = "http"), BindingElement (Protocol = "net.tcp"),
                             BindingElement (Protocol = "net.pipe"), BindingElement (Protocol = "net.msmq")…}
FtpServer                  : FtpServerSettings
Id                         : 1
Limits                     : SiteLimits
LogFile                    : SiteLogFile
Name                       : Default Web Site
ServerAutoStart            : true
TraceFailedRequestsLogging : TraceFailedRequestsLogging
VirtualDirectoryDefaults   : VirtualDirectoryElementDefaults

This now works because the WSMAN stacks on the local and remote machine are now running at version 3.0

Conclusions
1. To access the root\webadministration classes locally via WMI cmdlets we use the default DCOM authentication
2. To access the root\webadministration classes remotely via WMI cmdlets we use Packet Privacy DCOM authentication (-Authentication 6) with PowerShell v2 or v3
3. To access the root\webadministration classes remotely via WSMAN cmdlets we don’t need an Authentication parameter with PowerShell v2 or PowerShell v3
4. To access the root\webadministration classes remotely via CIM cmdlets the local and remote machine need to be running PowerShell v3 and WSMAN 3.0


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: