PowerShell for Windows Admins


December 20, 2011  1:54 PM

Recordings, Slides and Demo scripts



Posted by: Richard Siddaway
PowerShell, User Group, WMI

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



Posted by: Richard Siddaway
PowerShell, WMI

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



Posted by: Richard Siddaway
PowerShell, WMI

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



Posted by: Richard Siddaway
PowerShell

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



Posted by: Richard Siddaway
PowerShell, WMI

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



Posted by: Richard Siddaway
PowerShell, WMI

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


December 7, 2011  3:09 PM

Backing up the WMI repository



Posted by: Richard Siddaway
PowerShell, WMI

The WMI repository is a collection of files. It can be easily backed up

function backup-wmirepository {            
 param(            
  [string]$path,            
  [switch]$force            
 )            
             
 if ($force){            
  if (Test-Path $path){Remove-Item -Path $path -Force}            
 }            
 else {            
   if (Test-Path $path){Throw "$path already exists"}            
 }            
 $exp = "winmgmt /backup $path"            
             
 Invoke-Expression -Command $exp             
            
}

The function will back up the repository to the given file unless the file exists. if you want the backup file overwritten use the force switch


December 5, 2011  1:41 PM

Testing the WMI repository



Posted by: Richard Siddaway
PowerShell, WMI

Occasionally the WMI database becomes corrupt. Strangely I have seen this happening more often recently because of the creation of virtual machines from templates – if the template is corrupt so will be the virtual machines.

With Windows Vista and above we can use the winmgmt utility to test the repository. I’ve gotten used to the verb-noun syntax of PowerShell so decided to create a wrapper rather than try and remember the syntax

function test-wmirepository {            
 param(            
  [string]$path            
 )            
             
 if ($path) {            
   if (-not(Test-Path $path)){            
    Throw "$path not found"            
   }            
   else {            
    $path            
    $exp = "winmgmt /verifyrepository $path"            
   }            
 }            
 else {            
  $exp = "winmgmt /verifyrepository"            
 }            
 Invoke-Expression -Command $exp            
            
}

 

The utility can test the repository (default) or if the path to a backup file is given then that can be tested instead.

PS> test-wmirepository

WMI repository is consistent

if you don’t get the message about the repository being consistent then you have a problem. We’ll see how to fix that later.

How do you take a backup of the repository? – We’ll get to that later as well


December 5, 2011  12:00 PM

WMI rising



Posted by: Richard Siddaway
PowerShell, WMI

Its not the name of a new film but something that is happening.  WMI has always been a very powerful technology but has suffered because it has a reputation of being difficult to use and hard to understand.

Some of that is true but there is a lot more information becoming available. I’ve noticed a lot of sites putting out WMI based PowerShell – Scripting Guy blog and powershell.com being the two that most readily come to mind.

There are some big changes to WMI coming in PowerShell v3 and Windows 8 – now is the right time to start preparing


December 4, 2011  2:17 PM

UK PowerShell Group–December 2011



Posted by: Richard Siddaway
PowerShell 3, PowerShell v2, User Group, WMI


When: Thursday, Dec 15, 2011 7:30 PM (GMT)


Where: Virtual

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

Discover how to use the WSMAN cmdlets to retreive WMI information and see a demo of the new WMI API’s CIM cmdlets in PowerShell v3 CTP 2

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: PJSH3M
    Entry Code: gG/C-75(m
    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.


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: