-
Using PowerShell To Check That Windows Server Services Set To Automatic Have Started
Posted on January 11th, 2012 2 commentsFollowing 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
Posted on December 14th, 2011 No commentsThe 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:- Copy this address and paste it into your web browser:
https://www.livemeeting.com/cc/usergroups/join
- 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. - Copy this address and paste it into your web browser:
-
Reporting on Windows File Server Shares and NTFS Permissions with PowerShell
Posted on December 8th, 2011 No commentsI 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
Posted on November 21st, 2011 No commentsI 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_WinEthLANEndpointThere 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 -NoTypeInformationsdf
HP, powershell, wmi HP, powershell, wmi -
Monitor Citrix License Usage With PowerShell
Posted on January 5th, 2011 2 commentsWMI 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 "user@domain.com" -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 "user@domain.com" }sdf
-
Exchange 2003 / WMI / PowerShell article over at http://www.simple-talk.com/
Posted on May 13th, 2009 No commentsSo 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.
-
Slides from MMMUG presentation
Posted on February 21st, 2009 No commentsAs promised to those who attended the MMMUG on Wednesday night my slides from that evening are available on my SkyDrive.
Enjoy.










