September 2011 - Posts

WMI provider and MOF file

WMI is installed as a series of providers. The information on creating the classes comes from MOF files. I was recently asked about a problem with a specific class & could it be restored – in this case it was easier to rebuild WMI as the provider created a large part of the root\cimv2 namespace (namespaces can require multiple namespaces to complete their creation).

That got me thinking about how you discover the mof file associated with a class. Which leads to

$ns = "root\cimv2"            
$class = "Win32_Logicaldisk"            
            
            
$p = Get-WmiObject -Namespace $ns -Class $class |             
select -f 1 |             
select -ExpandProperty qualifiers |             
where {$_.Name -eq 'provider'}            
            
$class            
$p            
            
Get-ChildItem -Path C:\Windows\System32\wbem -Filter "*$($p.Value)*"

Get the first instance of a class, expand the qualifiers and select the qualifier with a name of provider.

Then perform a dir on the wbem folder to find the appropriate files. This isn’t infallible due to files names not necessarily being consistent but its a good starting point for the standard classes

Posted by RichardSiddaway | with no comments
Filed under:

Proxy function for Get-WmiObject

There are many people who don’t like to see the WMI system properties

PS> Get-WmiObject -Class Win32_OperatingSystem | select __*


__GENUS          : 2
__CLASS          : Win32_OperatingSystem
__SUPERCLASS     : CIM_OperatingSystem
__DYNASTY        : CIM_ManagedSystemElement
__RELPATH        : Win32_OperatingSystem=@
__PROPERTY_COUNT : 63
__DERIVATION     : {CIM_OperatingSystem, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER         : RSLAPTOP01
__NAMESPACE      : root\cimv2
__PATH           :
\\RSLAPTOP01\root\cimv2:Win32_OperatingSystem=@

Now one day we may get a version of Get-WmiObject that allows us to block their display but in the mean time we can create a proxy function.

Using the metaprogramming module from

http://blogs.msdn.com/powershell/archive/2009/01/04/extending-and-or-modifing-commands-with-proxies.aspx

I created a proxy function

New-ProxyCommand Get-WmiObject -CommandType All
-AddParameter NoSystemProperties > Get-WmiObject.ps1

This adds a parameter NoSystemProperties and outputs everything to a .ps1 file.

The details need to be added:

  1. turn the script into a function
  2. add the [switch] type to the property
  3. add the code to deal with the new parameter

 

if ($NoSystemProperties) {
[Void]$PSBoundParameters.Remove("NoSystemProperties")
$scriptCmd = {& $wrappedCmd @PSBoundParameters |
Select-Object -ExcludeProperty __*  -Property *|
Select-Object -ExcludeProperty Scope, Path, Options, ClassPath,
Properties, SystemProperties, Qualifiers, Site, Container -Property * }
}
else {
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
}

If the NoSystemProperties parameter is given then remove it from the bound parameters and then run get-wmiobject, exclude the system properties and then exclude the other related properties

If the NoSystemProperties isn’t set then run as normal

function Get-WmiObject {            
            
[CmdletBinding(DefaultParameterSetName='query')]            
param(            
    [Parameter(ParameterSetName='query', Mandatory=$true, Position=0)]            
    [Parameter(ParameterSetName='list', Position=1)]            
    [System.String]            
    ${Class},            
            
    [Parameter(ParameterSetName='list')]            
    [Switch]            
    ${Recurse},            
            
    [Parameter(ParameterSetName='query', Position=1)]            
    [System.String[]]            
    ${Property},            
            
    [Parameter(ParameterSetName='query')]            
    [System.String]            
    ${Filter},            
            
    [Switch]            
    ${Amended},            
            
    [Parameter(ParameterSetName='query')]            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Switch]            
    ${DirectRead},            
            
    [Parameter(ParameterSetName='list')]            
    [Switch]            
    ${List},            
            
    [Parameter(ParameterSetName='WQLQuery', Mandatory=$true)]            
    [System.String]            
    ${Query},            
            
    [Switch]            
    ${AsJob},            
            
    [Parameter(ParameterSetName='class')]            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='query')]            
    [Parameter(ParameterSetName='list')]            
    [Parameter(ParameterSetName='path')]            
    [System.Management.ImpersonationLevel]            
    ${Impersonation},            
            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='class')]            
    [Parameter(ParameterSetName='path')]            
    [Parameter(ParameterSetName='query')]            
    [Parameter(ParameterSetName='list')]            
    [System.Management.AuthenticationLevel]            
    ${Authentication},            
            
    [Parameter(ParameterSetName='class')]            
    [Parameter(ParameterSetName='list')]            
    [Parameter(ParameterSetName='path')]            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='query')]            
    [System.String]            
    ${Locale},            
            
    [Parameter(ParameterSetName='query')]            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='list')]            
    [Parameter(ParameterSetName='path')]            
    [Parameter(ParameterSetName='class')]            
    [Switch]            
    ${EnableAllPrivileges},            
            
    [Parameter(ParameterSetName='list')]            
    [Parameter(ParameterSetName='class')]            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='path')]            
    [Parameter(ParameterSetName='query')]            
    [System.String]            
    ${Authority},            
            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='path')]            
    [Parameter(ParameterSetName='class')]            
    [Parameter(ParameterSetName='query')]            
    [Parameter(ParameterSetName='list')]            
    [System.Management.Automation.PSCredential]            
    ${Credential},            
            
    [System.Int32]            
    ${ThrottleLimit},            
            
    [Parameter(ParameterSetName='list')]            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='path')]            
    [Parameter(ParameterSetName='class')]            
    [Parameter(ParameterSetName='query')]            
    [Alias('Cn')]            
    [ValidateNotNullOrEmpty()]            
    [System.String[]]            
    ${ComputerName},            
            
    [Parameter(ParameterSetName='list')]            
    [Parameter(ParameterSetName='path')]            
    [Parameter(ParameterSetName='class')]            
    [Parameter(ParameterSetName='WQLQuery')]            
    [Parameter(ParameterSetName='query')]            
    [Alias('NS')]            
    [System.String]            
    ${Namespace},            
                
    [Switch]            
    ${NoSystemProperties})            
            
begin            
{            
    try {            
        $outBuffer = $null            
        if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))            
        {            
            $PSBoundParameters['OutBuffer'] = 1            
        }            
        $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-WmiObject', [System.Management.Automation.CommandTypes]::Cmdlet)            
        if ($NoSystemProperties) {            
          [Void]$PSBoundParameters.Remove("NoSystemProperties")            
          $scriptCmd = {& $wrappedCmd @PSBoundParameters |             
             Select-Object -ExcludeProperty __*  -Property *|             
             Select-Object -ExcludeProperty Scope, Path, Options, ClassPath, Properties, SystemProperties, Qualifiers, Site, Container -Property * }            
        }            
        else {            
          $scriptCmd = {& $wrappedCmd @PSBoundParameters }            
        }              
        $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)            
        $steppablePipeline.Begin($PSCmdlet)            
    } catch {            
        throw            
    }            
}            
            
process            
{            
    try {            
        $steppablePipeline.Process($_)            
    } catch {            
        throw            
    }            
}            
            
end            
{            
    try {            
        $steppablePipeline.End()            
    } catch {            
        throw            
    }            
}            
            
<#

.ForwardHelpTargetName Get-WmiObject
.ForwardHelpCategory Cmdlet

#>            
            
}

The new function can be dot sourced or loaded from a module and because PowerShell runs functions before cmdlets it intercepts the cmdlet.

Get-WmiObject -Class Win32_OperatingSystem
Get-WmiObject -Class Win32_OperatingSystem –NoSystemProperties

then give us what we want.

The drawback is that using –NoSystemProperties we lose the methods but if you want them then you are either putting the results into an object or onto the pipeline in which case the system properties won’t be displayed.

Until we get a change to the cmdlet this will work.

Enjoy.

Posted by RichardSiddaway | with no comments
Filed under:

PowerShell 3 and DHCP 2: scopes

In this post http://msmvps.com/blogs/richardsiddaway/archive/2011/09/20/powershell-and-dhcp-1-servers.aspx

I showed how we could discover DHCP server information

Scopes can be discovered

Get-DhcpServerv4Scope -ComputerName server02  -ScopeId 10.10.54.0

Now how do we create a scope?

We use Add-DhcpServerv4Scope. Now shouldn’t that have been New-DhcpServerv4Scope?

Never the less this is how it works

Add-DhcpServerv4Scope -ComputerName server02 -Name TestScope 
-StartRange 192.168.100.1 -EndRange 192.168.100.200
-Description "Scope for testing" -Type DHCP
-State Active -SubnetMask 255.255.255.0
-LeaseDuration (New-TimeSpan -Days 1)

Type can be Dhcp,Bootp or Both

State can be Active or InActive

This creates and activates the scope

To inactivate a scope

Set-DhcpServerv4Scope -ComputerName server02
-ScopeId 192.168.100.0
-State Inactive

To reactivate

Set-DhcpServerv4Scope -ComputerName server02
-ScopeId 192.168.100.0
-State Active

To create a reservation

Add-DhcpServerv4Reservation -ComputerName server02
-ScopeId 192.168.100.0 -IPAddress 192.168.100.190
-ClientId 00-01-02-03-04-05 -Name Test57 
-Description "Exclusion for test device"

The ClientId is the MAC address (this one is made up)

To view the scopes reservations

Get-DhcpServerv4Reservation -ComputerName server02 -ScopeId 192.168.100.0

To remove a reservation

Remove-DhcpServerv4Reservation -ComputerName server02
-ScopeId 192.168.100.0 -ClientId 00-01-02-03-04-05

PowerShell remoting and the customisation of remoting end points–recording

The recording of Aleksandar’s session for the UK user group

http://msmvps.com/blogs/richardsiddaway/archive/2011/09/08/powershell-user-group-20-september-2011.aspx

entitled

PowerShell remoting and the customisation of remoting end points

Is available from

https://skydrive.live.com/?cid=43cfa46a74cf3e96#!/?cid=43cfa46a74cf3e96&sc=documents&uc=1&id=43CFA46A74CF3E96%212927

 

The slides and demo scripts are included in the zip file.

The next meeting will be 25 Oct  2011 on WSMAN and WMI.  It is an extended version of the recent session I did for the pre-TechEd Australia PowerShell conference. As well as WMI and WSMAN we will have a look at the new remoting access methods in PowerShell v3. Details to follow.

Posted by RichardSiddaway | with no comments

select-object quirk

I was working with the new CIM cmdlets in PowerShell 3 CTP and mistyped a command (as I thought)

Get-Cimclass win32_operatingsystem | select -ExpandProperty methods | select -f 1 select -ExpandProperty Qualifiers

 

My surprise was because of the two uses of select without a pipe between them.  It works, I don’t know why – but I don’t recommend it Smile

Posted by RichardSiddaway | with no comments

PowerShell Deep Dive speakers

Some more sessions have been announced for the Deep Dive

http://www.theexpertsconference.com/europe/2011/powershell-deep-dive/session-abstracts/

The speaker line up includes:

Aleksandar Nikolic

Shay Levy

Kirk Munro

Dmitry Sotnikov

Jeffery Hicks

James Brundage

Tobias Weltner

Brandon Shell

James O’Neill

Ravi Chaganti

Me

 

There will also be a significant presence from the PowerShell team.

 

If you can’t get your PowerShell questions answered here – then you won’t get them answered

PowerShell and DHCP: 1 – servers

Remember that yesterday I loaded the RSAT tools on to my Windows 8 server instance. This includes a PowerShell module that auto loads – like all Windows 8 modules on the PS module path

Start by looking at the GET commands

Get-Command -Module DhcpServer   get*

Get-DhcpServerAuditLog
Get-DhcpServerDatabase
Get-DhcpServerInDC
Get-DhcpServerSetting
Get-DhcpServerv4Binding
Get-DhcpServerv4Class
Get-DhcpServerv4DnsSetting
Get-DhcpServerv4ExclusionRange
Get-DhcpServerv4Failover
Get-DhcpServerv4Filter
Get-DhcpServerv4FilterList
Get-DhcpServerv4FreeIPAddress
Get-DhcpServerv4Lease
Get-DhcpServerv4OptionDefinition
Get-DhcpServerv4OptionValue
Get-DhcpServerv4Policy
Get-DhcpServerv4PolicyIPRange
Get-DhcpServerv4Reservation
Get-DhcpServerv4Scope
Get-DhcpServerv4ScopeStatistics
Get-DhcpServerv4Statistics
Get-DhcpServerv4Superscope
Get-DhcpServerv6Binding
Get-DhcpServerv6Class
Get-DhcpServerv6DnsSetting
Get-DhcpServerv6ExclusionRange
Get-DhcpServerv6FreeIPAddress
Get-DhcpServerv6Lease
Get-DhcpServerv6OptionDefinition
Get-DhcpServerv6OptionValue
Get-DhcpServerv6Reservation
Get-DhcpServerv6Scope
Get-DhcpServerv6ScopeStatistics
Get-DhcpServerv6StatelessStatis...
Get-DhcpServerv6StatelessStore
Get-DhcpServerv6Statistics
Get-DhcpServerVersion

 

This will keep us busy for a while and we haven’t looked at the other verbs!

Notice we don’t have a get-dhcpserver as such but we do have Get-DhcpServerVersion

 

PS> Get-DhcpServerVersion -ComputerName server02


MajorVersion : 6
MinorVersion : 1

 

PS> Get-WmiObject Win32_OperatingSystem -ComputerName server02 | fl Caption, version


Caption : Microsoft Windows Server 2008 R2 Datacenter
version : 6.1.7601

 

All we need is a bit of a wrapper function to decode the version numbers

 

also server settings

PS> Get-DhcpServerSetting -ComputerName server02


IsDomainJoined            : True
IsAuthorized              : True
DynamicBootp              : True
RestoreStatus             : False
ConflictDetectionAttempts : 0
NpsUnreachableAction      : Full
NapEnabled                : True
ActivatePolicies          :

 

Scopes are fairly important

 

PS> Get-DhcpServerv4Scope -ComputerName server02 | fl *


ScopeId          : 10.10.54.0
SubnetMask       : 255.255.255.0
StartRange       : 10.10.54.246
EndRange         : 10.10.54.250
ActivatePolicies :
Delay            : 0
Description      : Only used for new servers - before a static address is defined
LeaseDuration    : 04:00:00
MaxBootpClients  : 4294967295
Name             : NewServers
NapEnable        : True
NapProfile       :
State            : Active
SuperscopeName   :
Type             : Dhcp
ComputerName     :

 

There are IPv6 equivalent cmdlets as well

 

checking on free addresses

PS> Get-DhcpServerv4FreeIPAddress -ComputerName server02 -ScopeId "10.10.54.0"
10.10.54.246

 

PS> Get-DhcpServerv4FreeIPAddress -ComputerName server02 -ScopeId "10.10.54.0" -NumAddress 10
WARNING: The requested number of free IP addresses could not be found.
10.10.54.246
10.10.54.247
10.10.54.248
10.10.54.249
10.10.54.250

 

PS> Get-DhcpServerv4ScopeStatistics -ScopeId "10.10.54.0" -ComputerName server02 | fl *


ScopeId                       : 10.10.54.0
AddressesFree                 : 5
AddressesFreeOnPartnerServer  :
AddressesFreeOnThisServer     :
AddressesInUse                : 0
AddressesInUseOnPartnerServer :
AddressesInUseOnThisServer    :
PendingOffers                 : 0
PercentageInUse               : 0
ReservedAddress               : 0
SuperscopeName                :
ComputerName                  :

 

and finally

Get-DhcpServerv4Lease -ComputerName server02 -ScopeId "10.10.54.0"

will return the leases

PowerShell 3 CTP1

Today’s big news is the release of CTP1 for PowerShell 3

http://www.microsoft.com/download/en/details.aspx?id=27548

It only runs on Windows 7 SP1 and Windows 2008 R2 SP1

Posted by RichardSiddaway | with no comments
Filed under:

Windows Server remote server admin tools

I added the RSAT tools using the server manager module

PS> Get-Command -Module servermanager

CommandType     Name
-----------     ----
Alias           Add-WindowsFeature
Alias           Remove-WindowsFeature
Cmdlet          Get-WindowsFeature
Cmdlet          Install-WindowsFeature
Cmdlet          Uninstall-WindowsFeature

Notice the name changes Add/Remove are now aliases with the cmdlets as install/uninstall

Use

Install-WindowsFeature -Name RSAT -IncludeAllSubFeature –Restart

to force the restart.

PowerShell needs to be running as an elevated shell to add features

The server needs a reboot before the tools are available for use

These modules are added

ADDSDeployment
RemoteAccess
WebAdministration
DnsServer
ADRMSAdmin
DFSN
GroupPolicy
NFS
Hyper-V
DhcpServer
BitLocker
ActiveDirectory
NetworkLoadBalancingClusters

PS> Get-DnsServer -ComputerName server02 | select -ExpandProperty ServerZone

ZoneName                     ZoneType        IsAutoCreated   IsDsIntegrated  IsReverseLookupZone  IsSigned
--------                     --------        -------------   --------------  -------------------  --------
_msdcs.Manticore.org         Primary         False           True            False                False
0.in-addr.arpa               Primary         True            False           True                 False
127.in-addr.arpa             Primary         True            False           True                 False
255.in-addr.arpa             Primary         True            False           True                 False
54.10.10.in-addr.arpa        Primary         False           True            True                 False
Manticore.org                Primary         False           True            False                False
TrustAnchors                 Primary         False           True            False                False

This working against my Win 2008 R2 DNS server – cool

And DHCP

Get-DhcpServerv4Scope -ComputerName server02

And Hyper-V

Get-VMHost -ComputerName server02

and AD

Get-ADDomainController

All of these work against my Win 2008 R2 domain

There is a mass to dig through here

Split-Path & UNC

split-path works with with UNC paths as well as normal paths

 

PS> $path = "\\UNCserver\TFSBuilds\componenet\v11.1\XS11.1\XS11.1_11.1.0.35"
PS> Split-Path -Path $path -Parent
\\UNCserver\TFSBuilds\componenet\v11.1\XS11.1

 

PS> Split-Path -Path (get-location) -Parent
C:\scripts

Posted by RichardSiddaway | with no comments
Filed under:

PowerShell 3 discovery

Having a quick look at the numbers of commands in PowerShell 3 on Windows 8 I get this

 

PS> (get-command -CommandType cmdlet).count
376
PS> (get-command -CommandType function).count
524

 

The numbers are even higher on Server 8 depending on what  features/roles you have loaded.

 

How do you keep track of all those commands – memorising 900 names is not going to happen never mind the reported 2000+ on the server.

The answer is to step up a level to the module. Remember the modules that are available or use

PS> Get-Module -ListAvailable


    Directory: C:\Scripts\Modules


ModuleType Name                      ExportedCommands
---------- ----                      ----------------
Manifest   SystemInfo                {Get-ComputerSystem, Get-OperatingSystem}


    Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Name                      ExportedCommands
---------- ----                      ----------------
Manifest   AppLocker                 {Set-AppLockerPolicy, Get-AppLockerPolicy, Test-AppLockerPolicy...
Manifest   Appx                      {Add-AppxPackage, Get-AppxPackageManifest, Get-AppxPackage...
Manifest   BitLocker                 {Get-EncryptableVolume, Get-EncryptableVolumes, Get-Protectors..
Manifest   BitsTransfer              {Add-BitsFile, Remove-BitsTransfer, Complete-BitsTransfer...
Manifest   BranchCache               {Add-BCDataCacheExtension, Clear-BCCache, Disable-BC...

 

Notice that the folder the module is contained is displayed – useful.

Alternatively refine the search

Get-Module -ListAvailable *dns*

One point to note is that Get-Module by default only shows the modules you’ve used!  A new PowerShell console shows

Microsoft.PowerShell.Core
Microsoft.PowerShell.Management

but

PS> get-module | select name

Name
----
Microsoft.PowerShell.Core
Microsoft.PowerShell.Management
Microsoft.PowerShell.Utility

because we’ve used select-object

Posted by RichardSiddaway | with no comments
Filed under:

DNS cmdlets in PowerShell 3

There are a number of modules related to DNS

ModuleType Name
---------- ----
Manifest   DnsClient
Manifest   DnsConfig
Binary     DnsLookup
Manifest   DnsNrpt

If we start with the DnsClient module we get these functions and cmdlets

Add-DnsClientNrptRule
Clear-DNSClientCache
Get-DNSClient
Get-DNSClientCache
Get-DnsClientEffectiveNrptPolicy
Get-DnsClientNrptGlobal
Get-DnsClientNrptRule
Get-DNSGlobalSettings
Get-DNSServerAddress
Remove-DnsClientNrptRule
Set-DNSClient
Set-DnsClientNrptGlobal
Set-DnsClientNrptRule
Set-DNSGlobalSettings
Resolve-DnsName

Knowing which DNS server the client is using

PS> Get-DNSServerAddress | select ElementName, Name

ElementName                                                 Name
-----------                                                 ----
Virtual Wireless                                            192.168.2.1
isatap.{E962BF88-1194-44A8-B30B-A65A4772C812}               192.168.2.1
Virtual LAN                                                 10.10.54.201
isatap.{EA0AB201-1381-4643-A67D-72C9C8860860}               10.10.54.201
Loopback Pseudo-Interface 1                                 fec0:0:0:ffff::1
Loopback Pseudo-Interface 1                                 fec0:0:0:ffff::2
Loopback Pseudo-Interface 1                                 fec0:0:0:ffff::3

and what the client has cached

Get-DNSClientCache | select Name, data

Name                                                        data
----                                                        ----
server02                                                    192.168.2.1
server02                                                    10.10.54.201
server02                                                    192.168.1.6
server02.manticore.org                                      192.168.2.1
server02.manticore.org                                      10.10.54.201
server02.manticore.org                                      192.168.1.6
watson.telemetry.microsoft.com

final one for the moment – is a replacement for nslookup

PS> Resolve-DnsName exch07


IP4Address   : 10.10.54.130
Name         : exch07.Manticore.org
Type         : A
CharacterSet : Unicode
Section      : Answer
DataLength   : 4
TTL          : 1200

UK User Group–Alexsandar

Quick reminder about the UK User group Live Meeting on remoting and end points presented by PowerShell MVP Alexsandar Nikolic.

Details and link to join from http://msmvps.com/blogs/richardsiddaway/archive/2011/09/08/powershell-user-group-20-september-2011.aspx

Aleksandar talked about this at the recent PowerShell Deep Dive. This will be good!

PowerShell v3 remoting

In the Developer Preview builds it looks like PowerShell remoting is enabled by default.

This is a good idea for test labs. Is it the right decision for a production environment?

It seems to work exactly as v2

 

The remote management capabilities are enhanced by the new WMI APIs and remote access methods

Posted by RichardSiddaway | with no comments
Filed under:

PowerShell 3 default formats

In PowerShell v2 if you had 5 or fewer properties to display the formatting would default to a table.  More than that and you got a list.

Rules appear to have changed in v3 in that I’m getting default formatting producing tables with 6 items – Win32_ComputerSystem (6 items) still reverts to a list so its the new stuff thats changed.

Not a big deal but it does change expectations slightly

Posted by RichardSiddaway | with no comments
Filed under:

More PowerShell modules than you know what to do with

After building a PowerShell Windows 8 server I naturally started to look at PowerShell

Click the icon and it loads

PS C:\Users\Administrator> $psversiontable

Name                           Value
----                           -----
PSVersion                      3.0
PSCompatibleVersions           {1.0, 2.0, 3.0}
BuildVersion                   6.2.8102.0
CLRVersion                     4.0.30319.17020
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.103
SerializationVersion           1.1.0.1

Compare with current details from PowerShell v2

PS> $psversiontable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5446
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

 

The biggest change is that PowerShell 3 uses .NET 4.0 and WSMan has moved on a version.

Without loading any features or roles the following 56 modules are available

ADDeploymentWF                           AppLocker
Appx                                     BestPractices
BitsTransfer                             BranchCache
CimCmdlets                               ClusterAwareUpdating
DirectAccessClientComponents             Dism
DnsClient                                DnsConfig
DnsLookup                                DnsNrpt
FailoverClusters                         FileServer
iSCSI                                    KdsCmdlets
Microsoft.PowerShell.Core                Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host                Microsoft.PowerShell.Management
Microsoft.PowerShell.Security            Microsoft.PowerShell.Utility
Microsoft.WSMan.Management               MicrosoftiSCSITarget
MsDtc                                    NetAdapter
NetLbfo                                  NetQos
NetSwitchTeam                            NetTCPIP
netwnv                                   NetworkConnectivityStatus
NetworkSecurity                          NetworkTransition
PKIClient                                PrintManagement
PS_MMAgent                               PSDiagnostics
PSScheduledJob                           PSWorkflow
RDManagement                             ScheduledTasks
SecureBoot                               ServerManager
ServerManagerShell                       SmbShare
SmbWitness                               Storage
TelemetryManagement                      TroubleshootingPack
TrustedPlatformModule                    UserAccessLogging
Wdac                                     Whea

These modules are auto loaded when PowerShell starts

                                          ADDeploymentWF
AppLocker                                Appx
BestPractices                            BitsTransfer
BranchCache                              CimCmdlets
ClusterAwareUpdating                     DirectAccessClientComponents
Dism                                     DnsClient
DnsConfig                                DnsLookup
DnsNrpt                                  FailoverClusters
FileServer                               iSCSI
KdsCmdlets                               Microsoft.PowerShell.Core Microsoft.PowerShell.Diagnostics         Microsoft.PowerShell.Host
Microsoft.PowerShell.Management          Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility             Microsoft.WSMan.Management
MicrosoftiSCSITarget                     MsDtc
NetAdapter                               NetLbfo
NetQos                                   NetSwitchTeam
NetTCPIP                                 netwnv
NetworkConnectivityStatus                NetworkSecurity
NetworkTransition                        PKIClient
PrintManagement                          PS_MMAgent
PSDiagnostics                            PSScheduledJob
PSWorkflow                               RDManagement
ScheduledTasks                           SecureBoot
ServerManager                            ServerManagerShell
SmbShare                                 SmbWitness
Storage                                  TelemetryManagement
TroubleshootingPack                      TrustedPlatformModule
UserAccessLogging                        Wdac
Whea

Thats all of them! 

To paraphrase a slogan from a well known software company – what do you want to automate today?

Remember – thats before we add any roles or features.

This going to be fun

The Experts Conference April 2011–My session

Dmitry has just posted the video of the session I did at the PowerShell deep dive @ TEC in April

http://dmitrysotnikov.wordpress.com/2011/09/14/video-richard-siddaway-wmi-gems-and-gotchas/

 

The session was entitled WMI: Hidden Gems and Gotchas

Links to the slides and demo scripts are also available on the post

Posted by RichardSiddaway | with no comments

Windows 8 and PowerShell 3

You will have started to see blogs about Windows 8 and PowerShell 3 due to Microsoft releasing a developers preview version on MSDN.  I’m currently building Windows 8 and Server 8 machines – more news when they are up and running

Posted by RichardSiddaway | with no comments
Filed under:

More timespan

Poking further into the timespan object consider this

PS> New-TimeSpan -Days -10


Days              : -10
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : -8640000000000
TotalDays         : -10
TotalHours        : -240
TotalMinutes      : -14400
TotalSeconds      : -864000
TotalMilliseconds : –864000000

This is the equivalent of

PS> $ts = New-TimeSpan -Days 10
PS> $ts


Days              : 10
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 8640000000000
TotalDays         : 10
TotalHours        : 240
TotalMinutes      : 14400
TotalSeconds      : 864000
TotalMilliseconds : 864000000

 

PS> $ts.Negate()


Days              : -10
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : -8640000000000
TotalDays         : -10
TotalHours        : -240
TotalMinutes      : -14400
TotalSeconds      : -864000
TotalMilliseconds : –864000000

or even

PS> (New-TimeSpan -Days 10).Add( (New-TimeSpan -Days 10).negate())


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 0
TotalDays         : 0
TotalHours        : 0
TotalMinutes      : 0
TotalSeconds      : 0
TotalMilliseconds : 0

 

Timespans do not deal in units greater than days

PS> New-TimeSpan -Days 500


Days              : 500
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 432000000000000
TotalDays         : 500
TotalHours        : 12000
TotalMinutes      : 720000
TotalSeconds      : 43200000
TotalMilliseconds : 43200000000

 

PS> (Get-Date -Date "1 January 2011") - (Get-Date -Date "1 January 1815")


Days              : 71588
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 61852032000000000
TotalDays         : 71588
TotalHours        : 1718112
TotalMinutes      : 103086720
TotalSeconds      : 6185203200
TotalMilliseconds : 6185203200000

Posted by RichardSiddaway | with no comments
Filed under:

Its a date

If you’ve used PowerShell for any length of time you have come across the Get-Date cmdlet

 

PS> Get-Date

13 September 2011 20:47:50

 

The cmdlet returns a .NET System.DateTime object.  The object has some methods we can use

PS> Get-Date | Get-Member -MemberType method

Add
AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds
AddTicks
AddYears
CompareTo
Equals
GetDateTimeFormats
GetHashCode
GetType
GetTypeCode
IsDaylightSavingTime
Subtract
ToBinary
ToFileTime
ToFileTimeUtc
ToLocalTime
ToLongDateString
ToLongTimeString
ToOADate
ToShortDateString
ToShortTimeString
ToString
ToUniversalTime

 

Notice the list of methods for adding to the date

AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds
AddTicks
AddYears

which we use like this

PS> (Get-Date).AddDays(2)

15 September 2011 20:50:52


PS> (Get-Date).AddHours(2)

13 September 2011 22:51:00


PS> (Get-Date).AddMilliseconds(250)

13 September 2011 20:51:20


PS> (Get-Date).AddMinutes(20)

13 September 2011 21:11:36


PS> (Get-Date).AddMonths(3)

13 December 2011 20:51:51


PS> (Get-Date).AddSeconds(35)

13 September 2011 20:52:38


PS> (Get-Date).AddTicks(3500)

13 September 2011 20:52:16


PS> (Get-Date).AddYears(3500)

13 September 5511 20:52:30

 

Now these are all going forward.  We don’t have methods for subtracting from a date but we can do this

PS> Get-Date

13 September 2011 20:53:47


PS> (Get-Date).AddDays(-2)

11 September 2011 20:54:01

 

We use the Add*** methods with a negative value

 

The other alternatives to this involve using a TimeSpan

PS> $ts = New-TimeSpan -Days 10
PS> (Get-Date) + $ts

23 September 2011 20:55:33


PS> (Get-Date).Add($ts)

23 September 2011 20:55:45


PS> (Get-Date) - $ts

03 September 2011 20:55:54


PS> (Get-Date).Subtract($ts)

03 September 2011 20:56:08

 

As with many things in PowerShell there are a number of ways to solve a problem

Posted by RichardSiddaway | with no comments
Filed under:
More Posts Next page »