Tag Archives: wmi

The Importance of Being On Time

In an Active Directory environment its typical for client machines to use a local domain controller as their time source, domain controllers with the PDC emulator for the domain and the PDC emulator for the root domain to synchronise time with an external source. In most circumstances the aim is to keep the time synchronised within a 5 minute tolerance level, this will ensure there are no issues with Kerberos authentication which has the 5 minute tolerance as part of its requirements.

For some applications a tolerance of 5 minutes is too large and can cause issues with the application. You may need to adjust items such as the polling interval to ensure that the time is within a lower tolerance, but first of all you need to know how far out of tolerance the servers within your environment are.

The below Get-WindowsTimeDifference function can help you out here. It will take a list of Windows computers as input and then compare their time to either a specified Time Server within the environment, or by default attempt to use the PDC emulator for the Root AD Domain (or failing that, the PDC emulator for the current domain). The default tolerance level is one minute, this can be altered with the ToleranceLevel parameter.

A common cause of time sync issues can be Windows servers in the DMZ, which are not members of the domain. Consequently, by default they will not sync with a local domain controller and may need to be manually configured to use a time server (which doesn’t always happen!). Checking the time for these servers may require alternate credentials, so the Credential parameter is provided for that purpose.

The example below demonstrates using a text file list of Windows Server names piped into Get-WindowsTimeDifference with one server out of synch when the ToleranceLevel has been set to 3 minutes.

function Get-WindowsTimeDifference {
<#
.SYNOPSIS
Get the time difference between a time server and Windows clients

.DESCRIPTION
Get the time difference between a time server and Windows clients

.PARAMETER  ReferenceComputer
Name of the computer to check time difference for

.PARAMETER  TimeServer
Name of a TimeServer to use instead of the PDC Emulator

.PARAMETER  ToleranceLevel
Amount in minutes to permit as an acceptable time difference. Default is 1

.PARAMETER  Credential
Supply a PSCredential to use alternative credentials for the WMI query

.EXAMPLE
PS C:\> Get-WindowsTimeDifference -ReferenceComputer Server01 -ToleranceLevel 2

.EXAMPLE

PS C:\> Get-Content servers.txt | Get-WindowsTimeDifference
-TimeServer TimeServer -ToleranceLevel 3 | Select ComputerName,SynchronisedStatus,TimeDeviation,TimeServer

.EXAMPLE
PS C:\> Get-Content servers.txt | Get-WindowsTimeDifference -Credential (Get-Credential)

.NOTES
Author: Jonathan Medd
Date: 16/03/2012
#>

[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the computer to check time difference for",
ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[Alias('CN','__SERVER','IPAddress','Server','Computername')]
[System.String]
$ReferenceComputer = $env:COMPUTERNAME,

[Parameter(Position=1)]
[System.String]
$TimeServer,

[Parameter(Position=2)]
[int]
$ToleranceLevel = 1,

[Parameter(Position=3)]
[System.Management.Automation.PSCredential]
$Credential
)

begin {

# If no TimeServer specified, retrive the PDC Emulator for the Root Domain and the Current Domain
if (-not($Timeserver)) {

$Forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $Forest.RootDomain)
$RootPDCEmulator = ([System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)).PdcRoleOwner.Name
$CurrentDomainPDCEmulator = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).PdcRoleOwner.Name

# Attempt a WMI query to the PDC Emulator for the Root Domain
try {

$PDCEmulator = (Get-WmiObject Win32_OperatingSystem -ComputerName $RootPDCEmulator -ErrorAction Stop).__Server

}

# If there is an error (such as blocked TCP ports or permissions) try the PDC Emulator for the Current Domain instead
catch [System.Exception] {

$PDCEmulator = (Get-WmiObject Win32_OperatingSystem -ComputerName $CurrentDomainPDCEmulator).__Server
}

}
}

process {

# If no TimeServer specified, calculate the time difference between the PDC Emulator and the Reference Computer
if (-not($Timeserver)) {

try {
$PDCEmulatorWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $PDCEmulator

if ($Credential){

$ReferenceComputerWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $ReferenceComputer -Credential $Credential -ErrorAction Stop

}

else {

$ReferenceComputerWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $ReferenceComputer -ErrorAction Stop

}

$PDCEmulatorTime = $PDCEmulatorWMI.ConvertToDateTime($PDCEmulatorWMI.LocalDateTime)
$ReferenceComputerTime = $ReferenceComputerWMI.ConvertToDateTime($ReferenceComputerWMI.LocalDateTime)
$TimeDeviation = $PDCEmulatorTime - $ReferenceComputerTime
}

# Catch any errors with the WMI query to the Reference Computer
catch [System.Exception] {

$TimeDeviation = "Unable to contact server"

}
}

else {

# If TimeSever is specified, calculate the time difference between the TimeServer and the Reference Computer
try {

$TimeServerWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $TimeServer

if ($Credential){

$ReferenceComputerWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $ReferenceComputer -Credential $Credential -ErrorAction Stop

}

else {

$ReferenceComputerWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $ReferenceComputer -ErrorAction Stop

}

$TimeServerTime = $TimeServerWMI.ConvertToDateTime($TimeServerWMI.LocalDateTime)
$ReferenceComputerTime = $ReferenceComputerWMI.ConvertToDateTime($ReferenceComputerWMI.LocalDateTime)
$TimeDeviation = $TimeServerTime - $ReferenceComputerTime

}

# Catch any errors with the WMI query to the Reference Computer
catch [System.Exception] {

$TimeDeviation = "Unable to contact server"

}

}
# Use the TimeDeviation variable to determine SynchronisedStatus and TimeDeviation to report
if ($TimeDeviation -eq "Unable to contact server"){

$SynchronisedStatus = "Unable to contact server"

}

elseif ([Math]::Abs(($TimeDeviation).Minutes) -ge $ToleranceLevel) {

$SynchronisedStatus = "Not Synchronised"
$TimeDeviation = [string]$TimeDeviation.Minutes +" Minute(s) " + [string]$TimeDeviation.Seconds +" Seconds"
}

else {

$SynchronisedStatus = "Synchronised"
$TimeDeviation = [string]$TimeDeviation.Minutes +" Minute(s) " + [string]$TimeDeviation.Seconds +" Seconds"
}

# Create custom objects to store the results
New-Object -TypeName PSObject -Property @{
ComputerName = $ReferenceComputer
SynchronisedStatus = $SynchronisedStatus
TimeDeviation = $TimeDeviation
TimeServer = if ($PDCEmulator) {$PDCEmulator} else {$TimeServer}

}
}

}

It may also be important to prove that time is synchronised across your VMware servers. The Get-ESXTimeDifference function will do this for you. In the below example a list of VMware servers is obtained froma text file and the time checked against the Root Domain PDC emulator using the default ToleranceLevel of 1 minute.

Note: Get-ESXTimeDifference requires PowerCLI installed and a connection to vCenter having already been made.


function Get-ESXTimeDifference {
<#
.SYNOPSIS
Get the time difference between a time server and ESX clients

.DESCRIPTION
Get the time difference between a time server and ESX clients

.PARAMETER  ReferenceComputer
Name of the computer to check time difference for

.PARAMETER  TimeServer
Name of a TimeServer to use instead of the PDC Emulator

.PARAMETER  ToleranceLevel
Amount in minutes to permit as an acceptable time difference. Default is 1

.EXAMPLE
PS C:\> Get-ESXTimeDifference -ReferenceComputer ESX01 -ToleranceLevel 2

.EXAMPLE

PS C:\> Get-VMHost ESX01 | Get-ESXTimeDifference
-TimeServer TimeServer -ToleranceLevel 3 | Select ComputerName,SynchronisedStatus,TimeDeviation,TimeServer

.NOTES
Author: Jonathan Medd
Date: 16/03/2012
#>

[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the computer to check time difference for",
ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[Alias('CN','__SERVER','IPAddress','Server','Computername','VMHost','Name')]
[System.String]
$ReferenceComputer,

[Parameter(Position=1)]
[System.String]
$TimeServer,

[Parameter(Position=2)]
[int]
$ToleranceLevel = 1
)

begin {

# If no TimeServer specified, retrive the PDC Emulator for the Root Domain and the Current Domain
if (-not($Timeserver)) {

$Forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $Forest.RootDomain)
$RootPDCEmulator = ([System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)).PdcRoleOwner.Name
$CurrentDomainPDCEmulator = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).PdcRoleOwner.Name

# Attempt a WMI query to the PDC Emulator for the Root Domain
try {

$PDCEmulator = (Get-WmiObject Win32_OperatingSystem -ComputerName $RootPDCEmulator -ErrorAction Stop).__Server

}

# If there is an error (such as blocked TCP ports or permissions) try the PDC Emulator for the Current Domain instead
catch [System.Exception] {

$PDCEmulator = (Get-WmiObject Win32_OperatingSystem -ComputerName $CurrentDomainPDCEmulator).__Server
}

}
}

process {

# If no TimeServer specified, calculate the time difference between the PDC Emulator and the Reference Computer
if (-not($Timeserver)) {

$PDCEmulatorWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $PDCEmulator

$PDCEmulatorTime = $PDCEmulatorWMI.ConvertToDateTime($PDCEmulatorWMI.LocalDateTime)

$ReferenceComputerTime = ((Get-View ((Get-VMHost $ReferenceComputer).ExtensionData.ConfigManager.DateTimeSystem)).QueryDateTime()).ToLocalTime()
$TimeDeviation = $PDCEmulatorTime - $ReferenceComputerTime

}

else {

# If TimeSever is specified, calculate the time difference between the TimeServer and the Reference Computer

$TimeServerWMI = Get-WmiObject Win32_OperatingSystem -ComputerName $TimeServer

$TimeServerTime = $TimeServerWMI.ConvertToDateTime($TimeServerWMI.LocalDateTime)
$ReferenceComputerTime = ((Get-View ((Get-VMHost $ReferenceComputer).ExtensionData.ConfigManager.DateTimeSystem)).QueryDateTime()).ToLocalTime()
$TimeDeviation = $TimeServerTime - $ReferenceComputerTime

}
# Use the TimeDeviation variable to determine SynchronisedStatus and TimeDeviation to report

if ([Math]::Abs(($TimeDeviation).Minutes) -ge $ToleranceLevel) {

$SynchronisedStatus = "Not Synchronised"
$TimeDeviation = [string]$TimeDeviation.Minutes +" Minute(s) " + [string]$TimeDeviation.Seconds +" Seconds"
}

else {

$SynchronisedStatus = "Synchronised"
$TimeDeviation = [string]$TimeDeviation.Minutes +" Minute(s) " + [string]$TimeDeviation.Seconds +" Seconds"
}

# Create custom objects to store the results
New-Object -TypeName PSObject -Property @{
ComputerName = $ReferenceComputer
SynchronisedStatus = $SynchronisedStatus
TimeDeviation = $TimeDeviation
TimeServer = if ($PDCEmulator) {$PDCEmulator} else {$TimeServer}

}
}

}

WMI Class Win32_OperatingSystem Caption Property May Contain a Trailing Space

The WMI Class Win32_OperatingSystem Caption property returns the particular version of Windows, e.g.:

Microsoft Windows Server 2008 R2 Enterprise  or

Microsoft(R) Windows(R) Server 2003, Enterprise Edition

I had a requirement when querying this via PowerShell to take different actions based on whether the OS was some flavour of 2003 or 2008 and was using the following switch statement :


switch ($OperatingSystem.Caption) {
"Microsoft Windows Server 2008 R2 Enterprise" {$OSBuild = "2008"; break}
"Microsoft(R) Windows(R) Server 2003, Enterprise Edition" {$OSBuild = "2003";    break}
"Microsoft(R) Windows(R) Server 2003, Standard Edition" {$OSBuild = "2003";    break}
default {$OSBuild = "Unknown"}
}


 

However, when querying a 2008 R2 server $OperatingSystem.Caption was not matching “Microsoft Windows Server 2008 R2 Enterprise”. To the naked eye the results looked the same:

However, if you compared them with the Compare-Object cmdlet PowerShell reported them as different:


Compare-Object -ReferenceObject $OperatingSystem.Caption -DifferenceObject "Microsoft Windows Server 2008 R2 Enterprise"


 

They are definitely both String objects:

So what else could be different? How about the String length:

Aha! Turns out the Caption property has a trailing space and consequently there is no match between the two objects. (A comment on the MSDN page also confirms this for Win 7).  We can get round this by removing any trailing spaces with the String Trim method:

Compare-Object -ReferenceObject $OperatingSystem.Caption.Trim() -DifferenceObject "Microsoft Windows Server 2008 R2 Enterprise"

So the switch statement becomes:


switch ($OperatingSystem.Caption.Trim()) {
"Microsoft Windows Server 2008 R2 Enterprise" {$OSBuild = "2008"; break}
"Microsoft(R) Windows(R) Server 2003, Enterprise Edition" {$OSBuild = "2003";    break}
"Microsoft(R) Windows(R) Server 2003, Standard Edition" {$OSBuild = "2003";    break}
default {$OSBuild = "Unknown"}
}

If you have found this page for this issue then I hope I have saved you some head scratching. 🙂

 

Using PowerShell To Check That Windows Server Services Set To Automatic Have Started

Following on from the blog post Testing TCP Port Response from PowerShell  which provided a means to check that servers had fully rebooted after a patching and reboot cycle, I needed to take this one step further and check that all of the Windows Services set to Automatic successfully started after the reboot.

This should be pretty straightforward since we have a Get-Service cmdlet. Unfortunately however, this cmdlet does not return a StartMode parameter, i.e. it’s not possible to tell whether the Startup Type has been set to Automatic, Manual or Disabled. This is quite a large gap in my opinon – if you agree with me you can vote to get it included in a future release here. Of course with PowerShell there’s usually another way to achieve the same objective and using Get-WMIObject it is possible to find out the Startup Type of the service.


Get-WmiObject Win32_Service -ComputerName $ComputerName -Filter "StartMode='Auto' AND State='Stopped' AND Name!='SysmonLog'"

Notice that we filter out the Perfmon service (SysmonLog) since it is rarely in a started state.

One other thing to watch out for in this script is that the section


catch [System.Exception]

which is there to catch any WMI queries that fail, e.g. the server hasn’t rebooted properly or the correct permissions do not exist to make the WMI query, will not pick up any of these failures. This is because try / catch will only catch terminating errors and the WMI failures are non terminating. We can work around this by setting:


$ErrorActionPreference = "Stop"

and then back to normal afterwards:


$ErrorActionPreference = "Continue"

The script accepts pipeline input, so for example you could run it like:


Get-Content servers.txt | ./Get-AutomaticServiceState.ps1

Here it is:


<#
.SYNOPSIS
Retrieves any Windows services set to Automatic and are not running

.DESCRIPTION
Retrieves any Windows services set to Automatic and are not running

.PARAMETER  ComputerName
Name of the computer to test the services for

.EXAMPLE
PS C:\> Get-AutomaticServiceState -ComputerName Server01

.EXAMPLE
PS C:\> Get-Content servers.txt | Get-AutomaticServiceState

.NOTES
Author: Jonathan Medd
Date: 11/01/2012
#>

[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the computer to test",
ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[Alias('CN','__SERVER','IPAddress','Server')]
[System.String]
$ComputerName
)

process {

try {

# Set ErrorActionPreference to Stop in order to catch non-terminating WMI errors
$ErrorActionPreference = "Stop"

# Query the server via WMI and exclude the Performance Logs and Alerts Service
$WMI = Get-WmiObject Win32_Service -ComputerName $ComputerName -Filter "StartMode='Auto' AND State='Stopped' AND Name!='SysmonLog'"

}

catch [System.Exception]

{
$WMI = “” | Select-Object SystemName,Displayname,StartMode,State
$WMI.SystemName = $ComputerName
$WMI.Displayname = "Unable to connect to server"
$WMI.StartMode = ""
$WMI.State = ""
}

finally {

$ErrorActionPreference = "Continue"

}

if ($WMI){

foreach ($WMIResult in $WMI){

$MYObject = “” | Select-Object ComputerName,ServiceName,StartupMode,State
$MYObject.ComputerName = $WMIResult.SystemName
$MYObject.ServiceName = $WMIResult.Displayname
$MYObject.StartupMode = $WMIResult.StartMode
$MYObject.State = $WMIResult.State
$MYObject
}
}
}

UK PowerShell User Group December 2011 – Use the WSMAN cmdlets to retreive WMI information

The UK PowerShell User Group for December 2011 will take place at 19.30 GMT on Thursday December 15t. The topic is ‘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’. I’m looking forward to seeing the new CIM cmdlets from V3 CTP2 since I haven’t had chance to play with those yet. Details from Richard Siddaway’s blog are below:

 

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.

 

Reporting on Windows File Server Shares and NTFS Permissions with PowerShell

I recently had a requirement to audit the Share and NTFS permissions of a Windows File Server. PowerShell contains the Get-ACL cmdlet which makes retreving the NTFS permissions fairly straightforward, but for the Share permissions it is not so easy, but we can make use of WMI and the Win32_LogicalShareSecuritySetting class.

The below forum post details some discussion around using this class to find the Share permissions and unsurprisingly the legendary Shay Levy provides the solution.

http://groups.google.com/group/powershell-users/browse_thread/thread/43f06ce172e68c38?pli=1

The following script makes use of this code and adds some parameters depending on your requirements.


<#
.SYNOPSIS
Retrieve report of share permissions

.DESCRIPTION
Retrieve report of share permissions

.PARAMETER  ComputerName
Computer name to retrieve share permissions from

.PARAMETER  Share
Name of the share to retrieve permissions from (optional)

.PARAMETER  OutputFile
Name of the file to output the report to (optional)

.EXAMPLE
PS C:\> Get-SharePermissions.ps1 -ComputerName Server01 -Share Share01 -OutputFile C:\Scripts\SharePermissions.csv

.EXAMPLE
PS C:\> Get-SharePermissions.ps1 -ComputerName Server01

.NOTES
Author: Jonathan Medd
Date: 06/12/2011
Version: 0.1

#>

[CmdletBinding()]
param(

[Parameter(Position=0)]
[System.String]
$ComputerName = '.',

[Parameter(Position=1)]
[System.String]
$Share,

[Parameter(Position=2)]
[System.String]
$OutputFile
)

function Translate-AccessMask($val){
Switch ($val)
{
2032127 {"FullControl"; break}
1179785 {"Read"; break}
1180063 {"Read, Write"; break}
1179817 {"ReadAndExecute"; break}
-1610612736 {"ReadAndExecuteExtended"; break}
1245631 {"ReadAndExecute, Modify, Write"; break}
1180095 {"ReadAndExecute, Write"; break}
268435456 {"FullControl (Sub Only)"; break}
default {$AccessMask = $val; break}
}
}

function Translate-AceType($val){
Switch ($val)
{
0 {"Allow"; break}
1 {"Deny"; break}
2 {"Audit"; break}
}
}

# Create calculated properties
$ShareProperty = @{n="Share";e={$ShareName}}
$AccessMask = @{n="AccessMask";e={Translate-AccessMask $_.AccessMask}}
$AceType = @{n="AceType";e={Translate-AceType $_.AceType}}
$Trustee = @{n="Trustee";e={$_.Trustee.Name}}

if ($Share){

$filter="name='$Share'"

$WMIQuery = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -ComputerName $ComputerName -filter $filter | ForEach-Object {
$ShareName = $_.name
$_.GetSecurityDescriptor().Descriptor.DACL | Select-Object $Shareproperty,$AccessMask,$AceType,$Trustee}
}

else {
$WMIQuery = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -ComputerName $ComputerName | ForEach-Object {
$ShareName = $_.name
$_.GetSecurityDescriptor().Descriptor.DACL | Select-Object $Share,$AccessMask,$AceType,$Trustee }
}

if ($OutputFile){
$WMIQuery | Export-Csv $OutputFile -NoTypeInformation
}

else {
$WMIQuery | Format-Table -AutoSize
}

 

For NTFS permissions Jeff Hicks has a very useful post for creating NTFS ACL reports.

http://jdhitsolutions.com/blog/2011/06/creating-acl-reports/

The following is a script based off some of the ideas in that post which you can use for generating a report depending on your requirements.


<#
.SYNOPSIS
Retrieve report of NTFS permissions

.DESCRIPTION
Retrieve report of NTFS permissions

.PARAMETER  ComputerName
Computer name to retrieve NTFS permissions from

.PARAMETER  Folder
Name of the NTFS path to retrieve permissions from

.PARAMETER  Recurse
Retrieve permissions from subfolders and files

.PARAMETER  OutputFile
Name of the file to output the report to (optional)

.EXAMPLE
PS C:\> Get-NTFSPermissions.ps1 -ComputerName Server01 -Folder D$\Home -OutputFile C:\Scripts\NTFSPermissions.csv

.EXAMPLE
PS C:\> Get-NTFSPermissions.ps1 -Folder D:\Home -Recurse

.NOTES
Author: Jonathan Medd
Date: 07/12/2011
Version: 0.1

#>

[CmdletBinding()]
param(

[Parameter(Position=0)]
[System.String]
$ComputerName = '.',

[Parameter(Position=1,Mandatory=$true,HelpMessage="Name of the NTFS path to retrieve permissions from")]
[System.String]
$Folder,

[Parameter(Position=2)]
[Switch]
$Recurse,

[Parameter(Position=3)]
[System.String]
$OutputFile
)

# Set the Path variable dependent on whether its for a remote machine
if ($ComputerName -eq '.'){
$Path = $Folder
}

else {
$Path = "\\$ComputerName\$Folder"
}

if ($OutputFile){
Get-Childitem $Path -Recurse:$Recurse | ForEach-Object {Get-Acl $_.FullName} | Select-Object @{Name="Path";Expression={$_.PSPath.Substring($_.PSPath.IndexOf(":")+2) }},@{Name="Type";Expression={$_.GetType()}},Owner -ExpandProperty Access | Export-CSV $OutputFile -NoTypeInformation
}

else {
Get-Childitem $Path -Recurse:$Recurse | ForEach-Object {Get-Acl $_.FullName} | Select-Object @{Name="Path";Expression={$_.PSPath.Substring($_.PSPath.IndexOf(":")+2) }},@{Name="Type";Expression={$_.GetType()}},Owner -ExpandProperty Access | Format-Table -AutoSize
}

Working with the HPQ WMI Provider to find NIC Information on HP Proliant Servers

I recently had a task to query NIC information on a number of HP Proliant servers, this included the connected NIC speed, duplex settings and status of the configured HP Team. I initally looked at the WMI class Win32_NetworkAdapterConfiguration  which contains a lot of info around NIC configuration. Unfortunately, it does not include NIC speed or duplex settings.

Looking for alternatives, I discovered a script from Hugo Peeters which instead queried the registry key HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318} which looked like it would do the job. However, for some reason this works fine for HP rackmount servers, but blades do not appear to publish NIC info to that registry key so I needed to look for something else.

A colleague pointed me to the HPQ WMI Provider, which I had not seen before and there does not appear to be a lot of published info about either. It can be installed as part of the HP Proliant installation process and adds 800+ classes that can be queried via WMI –  a sample is shown below from the Root\HPQ Namespace:

In this instance, I was able to use the following classes to obtain the information I needed:

HP_EthernetTeam
HP_EthernetPort
HP_WinEthLANEndpoint

There is an absolute wealth of information stored in here, so I would encourage you to check it out if you work with Windows Server on HP systems. The script I put together puts together a basic report of some key NIC info, with the knowledge that there are never more than 4 NICs in a server being queried.

Note that I have used the parameter -ErrorAction Stop in the WMI queries, to enforce a terminating error to be generated if the WMI query fails. Without this, the error is non-terminating and does not get caught by the Catch statement.


$HP_EthernetTeam = Get-WmiObject -Namespace root\hpq -Class HP_EthernetTeam -ComputerName $ComputerName -ErrorAction Stop


<#
.SYNOPSIS
Retrieve HP NIC Info from HPQ WMI Namespace

.DESCRIPTION
Retrieve HP NIC Info from HPQ WMI Namespace

.PARAMETER  ServersInputFile
Path to the file containing server names

.PARAMETER  OutputFile
Path to the csv file to output data to

.EXAMPLE
PS C:\> Get-HPNICStatus.ps1 -ServersInputFile C:\Scripts\Servers.txt -OutputFile C:\Scripts\HPNICStatus.csv

#>

[CmdletBinding()]
param(

[Parameter(Position=0,Mandatory=$true,HelpMessage="Path to the file containing server names")]
[System.String]
$ServersInputFile,

[Parameter(Position=1,Mandatory=$true,HelpMessage="Path to the csv file to output data to")]
[System.String]
$OutputFile
)

$ComputerNames = Get-Content $ServersInputFile

# Allow conversion to MB/sec for NIC speed
$NICSpeedConversionConstant = 1000000

$myCol = @()

foreach ($ComputerName in $ComputerNames){

Write-Host "`n`n"
Write-Host "Querying NIC info on $ComputerName"

# Test for HPQ WMI Namespace and deal with a failure in catch statement
try {

$HP_EthernetTeam = Get-WmiObject -Namespace root\hpq -Class HP_EthernetTeam -ComputerName $ComputerName -ErrorAction Stop
$HP_EthernetPort = Get-WmiObject -Namespace root\hpq -Class HP_EthernetPort -ComputerName $ComputerName -ErrorAction Stop
$HP_WinEthLANEndpoint = Get-WmiObject -Namespace root\hpq -Class HP_WinEthLANEndpoint -ComputerName $ComputerName -ErrorAction Stop

Write-Host "Successful query on $ComputerName"

# Calculate Team Health Status based on WMI query result
switch ($HP_WinEthLANEndpoint.HealthState) {
"0" {$HPTeamStatus = "Unknown"; break}
"5" {$HPTeamStatus = "OK"; break}
"10" {$HPTeamStatus = "Degraded/Warning"; break}
"15" {$HPTeamStatus = "Minor Failure"; break}
"20" {$HPTeamStatus = "Major Failure"; break}
"25" {$HPTeamStatus = "Critical Failure"; break}
"30" {$HPTeamStatus = "Non-recoverable Error"; break}
default {$HPTeamStatus = "Unknown"}
}

# Check Ethernet Port Status
$EthernetPortHealthStateArray = @()

foreach ($EthernetPort in $HP_EthernetPort){

switch ($EthernetPort.HealthState) {
"0" {$EthernetPortHealthState = "Unknown"; break}
"5" {$EthernetPortHealthState = "OK"; break}
"10" {$EthernetPortHealthState = "Degraded/Warning"; break}
"15" {$EthernetPortHealthState = "Minor Failure"; break}
"20" {$EthernetPortHealthState = "Major Failure"; break}
"25" {$EthernetPortHealthState = "Critical Failure"; break}
"30" {$EthernetPortHealthState = "Non-recoverable Error"; break}
default {$EthernetPortHealthState = "Unknown"}
}

$EthernetPortHealthStateObject = "" | Select-Object EthernetPortName,EthernetPortHealthStatus
$EthernetPortHealthStateObject.EthernetPortName = $EthernetPort.Description
$EthernetPortHealthStateObject.EthernetPortHealthStatus = $EthernetPortHealthState
$EthernetPortHealthStateArray += $EthernetPortHealthStateObject

}

$MYObject = “” | Select-Object Servername,HPTeamName,HPTeamStatus,HPTeamSpeed,NIC1Description,NIC1Model,NIC1Speed,NIC1FullDuplex,NIC1HealthState,NIC2Description,NIC2Model,NIC2Speed,NIC2FullDuplex,NIC2HealthState,NIC3Description,NIC3Model,NIC3Speed,NIC3FullDuplex,NIC3HealthState,NIC4Description,NIC4Model,NIC4Speed,NIC4FullDuplex,NIC4HealthState
$MYObject.Servername = $ComputerName
$MYObject.HPTeamName = $HP_EthernetTeam.Description
$MYObject.HPTeamStatus = $HPTeamStatus
$MYObject.HPTeamSpeed = [string]($HP_EthernetTeam.Speed / $NICSpeedConversionConstant) + " MB/sec"
$MYObject.NIC1Description = $HP_EthernetPort[0].Description
$MYObject.NIC1Model = $HP_EthernetPort[0].Caption
$MYObject.NIC1Speed = [string]($HP_EthernetPort[0].Speed / $NICSpeedConversionConstant) + " MB/sec"
$MYObject.NIC1FullDuplex = $HP_EthernetPort[0].FullDuplex
$MYObject.NIC1HealthState = $EthernetPortHealthStateArray[0].EthernetPortHealthStatus
$MYObject.NIC2Description = $HP_EthernetPort[1].Description
$MYObject.NIC2Model = $HP_EthernetPort[1].Caption
$MYObject.NIC2Speed = [string]($HP_EthernetPort[1].Speed / $NICSpeedConversionConstant) + " MB/sec"
$MYObject.NIC2FullDuplex = $HP_EthernetPort[1].FullDuplex
$MYObject.NIC2HealthState = $EthernetPortHealthStateArray[1].EthernetPortHealthStatus
$MYObject.NIC3Description = $HP_EthernetPort[2].Description
$MYObject.NIC3Model = $HP_EthernetPort[2].Caption
$MYObject.NIC3Speed = if ($HP_EthernetPort[2].Speed -ne $null){[string]($HP_EthernetPort[2].Speed / $NICSpeedConversionConstant) + " MB/sec"}
$MYObject.NIC3FullDuplex = $HP_EthernetPort[2].FullDuplex
$MYObject.NIC3HealthState = $EthernetPortHealthStateArray[2].EthernetPortHealthStatus
$MYObject.NIC4Description = $HP_EthernetPort[3].Description
$MYObject.NIC4Model = $HP_EthernetPort[3].Caption
$MYObject.NIC4Speed = if ($HP_EthernetPort[3].Speed -ne $null){[string]($HP_EthernetPort[3].Speed / $NICSpeedConversionConstant) + " MB/sec"}
$MYObject.NIC4FullDuplex = $HP_EthernetPort[3].FullDuplex
$MYObject.NIC4HealthState = $EthernetPortHealthStateArray[3].EthernetPortHealthStatus
$myCol += $MYObject
}

# If WMI query fails
catch {

Write-Host "Unsuccessful query on $ComputerName"

$MYObject = “” | Select-Object Servername,HPTeamName,HPTeamStatus,HPTeamSpeed,NIC1Description,NIC1Model,NIC1Speed,NIC1FullDuplex,NIC1HealthState,NIC2Description,NIC2Model,NIC2Speed,NIC2FullDuplex,NIC2HealthState,NIC3Description,NIC3Model,NIC3Speed,NIC3FullDuplex,NIC3HealthState,NIC4Description,NIC4Model,NIC4Speed,NIC4FullDuplex,NIC4HealthState
$MYObject.Servername = $ComputerName
$MYObject.HPTeamName = "HPQ WMI is not installed or WMI query failed"
$MYObject.HPTeamStatus = "N/A"
$MYObject.HPTeamSpeed = "N/A"
$MYObject.NIC1Description = "N/A"
$MYObject.NIC1Model = "N/A"
$MYObject.NIC1Speed = "N/A"
$MYObject.NIC1FullDuplex = "N/A"
$MYObject.NIC1HealthState = "N/A"
$MYObject.NIC2Description = "N/A"
$MYObject.NIC2Model = "N/A"
$MYObject.NIC2Speed = "N/A"
$MYObject.NIC2FullDuplex = "N/A"
$MYObject.NIC2HealthState = "N/A"
$MYObject.NIC3Description = "N/A"
$MYObject.NIC3Model = "N/A"
$MYObject.NIC3Speed = "N/A"
$MYObject.NIC3FullDuplex = "N/A"
$MYObject.NIC3HealthState = "N/A"
$MYObject.NIC4Description = "N/A"
$MYObject.NIC4Model = "N/A"
$MYObject.NIC4Speed = "N/A"
$MYObject.NIC4FullDuplex = "N/A"
$MYObject.NIC4HealthState = "N/A"
$myCol += $MYObject
}

Clear-Variable HP_EthernetTeam,HP_EthernetPort,HP_WinEthLANEndpoint,HPTeamStatus,EthernetPortHealthStateArray,EthernetPortHealthStateObject,EthernetPortHealthStateArray

}

$myCol | Export-Csv $OutputFile -NoTypeInformation

sdf

Monitor Citrix License Usage With PowerShell

WMI in Windows Server is a treasure trove of information and well worth investigating, particularly when needing to run reports against many servers. In addition it is possible for third-parties to make use of WMI and store their own information in there. This is true of a recent requirement I had to monitor Citrix Licensing.

Whilst it’s obviously critical to purchase enough licenses for Citrix that you need, its also important to not have too many lying around not in use, since you’ll be wasting money.  Given that Citrix Licensing is based on concurrency you may have different usage patterns at the time of day, month or year.

Contained within the WMI Namespace ROOT\CitrixLicensing is a class Citrix_GT_License_Pool. In this class you can find details for registered licenses and how many are in use. The PowerShell cmdlet Get-WMIObject can be used to retrieve this information. Once you have it you could save the report into a CSV file, write an entry to an event log or send an email alert.

The below example will generate an email alert when then level of licenses in use goes over 90%. The email will contain basic details of how many licenses are currently in use.


<#
.SYNOPSIS
 Report on Citrix License Usage
.DESCRIPTION
 Report on Citrix License Usage
.NOTES
 Authors:Jonathan Medd
.PARAMETER CitrixLicenseServer
 Name of Citrix License Server
.EXAMPLE
 Get-CitrixLicenseUsage -CitrixLicenseServer Server01
#>
param (
 [parameter(Mandatory=$True,HelpMessage='Name of Citrix License Server')]
 $CitrixLicenseServer
 )

# Get Citrix Licensing Info from WMI
$LicensePool = Get-WmiObject -class "Citrix_GT_License_Pool" -Namespace "ROOT\CitrixLicensing" -ComputerName $LicenseServer

# Calculate licenses in use, total number of licenses and percentage currently in use
$InUseNum = ($LicensePool | Measure-Object -Property InUseCount -sum).Sum
$InstalledLicNum = ($LicensePool | Measure-Object -Property Count -sum).Sum
$PercentageNum = [math]::round(($InUseNum/$InstalledLicNum)*100,2)

# Check the usage and send an email if over 90%
if ($PercentageNum -lt 90)
{
}
else
{
Send-MailMessage -To "[email protected]" -Subject "Citrix License Server Statistics For $CitrixLicenseServer" -Body "The below is the current status of the license server:`n`nInstalled Licences: $InstalledLicNum`n`nLicences In Use: $InUseNum`n`nPercentage: $PercentageNum%" -SmtpServer "smtpserver" -From "[email protected]"
}


sdf

Exchange 2003 / WMI / PowerShell article over at http://www.simple-talk.com/

So I got asked to write an article for the http://www.simple-talk.com/ website, a well known online technical journal and community hub around SQL and .NET technologies. They’ve recently been branching out into Exchange as well hence they reason they were looking for some Exchange based articles.

The article I have written for them is based around a presentation I have made around some user groups a few times now, i.e. using PowerShell and WMI to manage Exchange 2003. I really enjoyed the process of transferring the content into a written article and hopefully I may get the opportunity to write some more so please check it out.

You can also take advantage of a free Sybex Best Of Exchange 2007 Server ebook by signing up for their Exchange newsletter.