Ying Li at myITforum.com

PowerShell & System Center

July 2008 - Posts

Where is PowerShell on Windows Server 2008

As you may already know that Windows PowerShell 1.0 for the first time included as part of the Windows Operating System on Windows Server 2008. But where is it on Windows Server 2008 - for a brand new install Windows Server 2008, you can't find it in Start - All Programs!

This is because Windows Sever 2008 is a role/service, feature based OS and by default it doesn't install or enable much.

Windows PowerShell is a feature need to be enabled on Windows Server 2008 box. See below figure:

Enable PowerShell on Windows Server 2008

Pushing OpsMgr SP1 Agent to Windows Server 2008

I have a couple of brand new Windows Server 2008 setup and trying to push OpsMgr agent to them but I got the below error:

The MOM Server would not execute WMI Query "Select * from Win32_Operatingsystem" on computer xyzsmsp02.whatever.com.

Operation:Agent Install

Install account: my domain admin account

Error Code: 800706BA

Error Description: The RPC server is unavailable

As we already know by default Windows Server 2008 doesn't install much and block "everything"!

All we have to do to fix the above error is to go to Windows Firewall on the Windows server 2008 box and enable WMI exception!

Posted: Jul 30 2008, 11:41 PM by yli628 | with no comments
Filed under:
How to detach SUSDB that is "currently in use"

I am setting up ConfigMgr SP1 on Windows Server 2008 and I installed WSUS 3.0 SP1 and the SUSDB resides on the same box with ConfigMgr Database. After the setup, I am trying to follow the SQL best practice to move the Logs to a different drive.

There are plenty posts on the web about how you move a SQL 2005 Database or Log files to a different place or you can search SQL online help:

Here are some of the recommend options:

1) Detach and re attach the Database;

2) Backup the Database and then restore.

But when I tried to detach SUSDB, I get the following error:

"Cannot detach the database 'SUSDB' because it is currently in use"

So who is using SUSDB?

IIS Admin Service

Update Services (Not Windows Update Service!)

You need to stop both service to successfully detach SUSDB!

You know how to do the rest.

PowerShell Script to retrieve scheduled tasks on a remote machine - Task Scheduler API

Rod Trent posted a PowerShell script for Getting the List of Scheduled Tasks. I have the need the other day to retrieve scheduled tasks on a remote server. I give it a try but to my surprise, it doesn't return anything while I know I have tasks scheduled on that box. Why?

This is because that Windows has two different APIs to manage scheduled tasks

1) The Task Scheduler API used by Task Scheduler and by Schtasks.exe, a command-line task management tool that ships with XP/Windows 2003 and beyond;

2) So called AT APIs  used by At.exe and by WMI's Win32_Scheduled class.

So Rod's script covered the AT API and apparently my tasks weren't scheduled that way and hence why I couldn't retrieve anything.

Now the question is can we use script, PowerShell in particular to retrieve the tasks scheduled using Task Scheduler API? Yes, we can! But you will need Windows Vista to accomplish that.

First we need to create an instance of Schedule.Service (COM) object, then we will need to use the connect method to actually connect to the service. By default it will connect to the local machine but you could specify a remote computer to connect to like below, we are connecting to a computer called "Whatever"

$ST = new-object -com("Schedule.Service")

$ST.connect("whatever")

Next we need to retrieve the object reference to the folder we want to search. In my case, that's the root folder(\):

$RootFolder = $ST.getfolder("\")

We then use the GetTasks method to get a collection of all the tasks in the folder targeted.

$ScheduledTasks = $root.GetTasks(0)

The parameter (0) to the GetTasks method is required - Why? I don't know!

Last but not least, We get what what we looking for - The tasks scheduled on the remote machine!

$ScheduledTasks | select name, path, enabled, lastruntime, nextruntime

Name        : WhateverUpdater
Path        : \WhateverUpdater
Enabled     : True
LastRunTime : 7/28/2008 4:30:00 AM
NextRunTime : 7/29/2008 4:30:00 AM

Name        : XYZ
Path        : \XYZ
Enabled     : True
LastRunTime : 7/28/2008 4:00:00 AM
NextRunTime : 7/29/2008 4:00:00 AM

Now with Rod's AT API and my Task Scheduler API, we get Scheduled Tasks covered!

Posted: Jul 28 2008, 08:24 PM by yli628 | with 6 comment(s)
Filed under:
OpsMgr: Why all my agents turn gray - OpsMgr Healthservice must run under local system account!!!

The other day, I was working with Quest support for the eXc Blackberry monitoring software. We tried to delete/import their MP. During the process, I will need to input the password for the account which OpsMgr SDK Service and OpsMgr Config Service are running under. I found the password and I want to verify it. I didn't use the SDK service to verify concerning that if I don't have the correct password, I will not be able to restart the service. So I use OpsMgr Healthservice instead thinking I could easily switch back to local system account. I did exactly that and a few minutes if not seconds later, I noticed that all my agents are grayed out (unknown status!).

At first, we thought this is because we deleted/import the MP -bogs down SQL database. I thought to let it run over the weekend and hoping that it will fix itself. On Monday, all the agents are still grayed out only the agent for the RMS is green. I called PSS support, MS engineer  determine this is because "Duplicate SPN". He did Setspn -l which didn't catch it or didn't catch all the duplicates. He then use MS internal VBscript to identify more duplicates. The moment after we clean up the "Duplicate SPN", we restarted the RMS and the agents are starting coming back green!

I mentioned that the OpsMgr Healthservice account "swap" to MS engineer but he didn't link this two events together. I did some digging and found out  that's exact the cause why all my agents turn gray. The Healthservice account (especially on RMS) must run under local system account or you will get duplicate SPN. Even after you switch the account back. Before I thought running under local system account is preferred but not knowing it is a "MUST"! I never realized that simply by change the OpsMgr Healthservice account on RMS can cause so much trouble and it costed me a support ticket. :)

Next time if all your agents are grayed out - Check your SPN first!

Posted: Jul 24 2008, 12:19 AM by yli628 | with no comments
Filed under:
PowerShell Script to identify Agent which needs to have "proxying" enabled

Every now and then, I get an alert like this:

Alert: Agent proxying needs to be enabled for a health service to submit discovery data about other computers.

Source: xyzopmp04.related.com

Path: xyzopmp04.related.com

Last modified by: System

Last modified time: 7/21/2008 8:18:46 PM Alert description: Details:Health service ( 9AAFF032-4567-2270-B09A-A34025D969F3 ) should not generate data about this managed object ( EC7903B7-72FC-BFD0-3CA2-473774E60AD4 ).

Alert view link: "http://XYZOPMP01:51908/default.aspx?DisplayMode=Pivot&AlertID={0b2c1100-f167-4691-b271-e209632392bf}"

Notification subscription ID generating this message: {4B6F3971-955E-1491-6D82-5C22F1466FC2

This is common and all we need to do is to identify the agent and then enable proxy.

How we translate something like this -  'EC7903B7-72FC-BFD0-3CA2-473774E60AD4' to the computer name?

1, We can run a SQL query in OperationManagerDB

select * from basemanagedentity where basemanagedentityid =
'EC7903B7-72FC-BFD0-3CA2-473774E60AD4'

2, We could use PowerShell

Save the below script as whatever.ps1

Param([string]$MonitoringObjectID)

Get-MonitoringObject -id $MonitoringObjectID | select name

Then run it from command shell console:

c:\MyWorkSpace\whatever.ps1 EC7903B7-72FC-BFD0-3CA2-473774E60AD4

Either way, you will get the computer name and then you can go to your OpsMgr console to enable proxying for the agent!

Technorati Tags: ,
PowerShell Script to work with DNS WMI Provider

The DNS WMI provider exposes a number of DNS objects, including DNS Servers, DNS domains, DNS Zones and DNS Resource Records etc. We could use these objects to manage DNS and you guess it, through PowerShell!

The DNS WMI Provider is installed on Windows Server 2003 by default. For Windows 2000, you could obtain the DNS WMI Provider from Windows 2000 Server Resource Kit or follow this Link

Here is a PowerShell script to list DNS Zones

Get-WmiObject -namespace "root\MicrosoftDNS" -class MicrosoftDNS_Zone -Credential DnsServer\Administrator -ComputerName DnsServer

This will list all the DNS zones on your DNS server(Microsoft DNS server, that is)!

If you want to see what other classes are there

Get-WmiObject -namespace "root\MicrosoftDNS" -Credential DnsServer\Admin
istrator -ComputerName DnsServer -list

__SystemClass                                               __NAMESPACE
__Provider                                                  __Win32Provider
__ProviderRegistration                                      __ObjectProviderRegistration
__ClassProviderRegistration                                 __InstanceProviderRegistration
__PropertyProviderRegistration                              __MethodProviderRegistration
__EventProviderRegistration                                 __EventConsumerProviderRegistration
__NotifyStatus                                              __ExtendedStatus
__CIMOMIdentification                                       __SecurityRelatedClass
__NTLMUser9X                                                __IndicationRelated
__Event                                                     __PARAMETERS
__ExtrinsicEvent                                            __NamespaceOperationEvent
__NamespaceCreationEvent                                    __NamespaceDeletionEvent
__NamespaceModificationEvent                                __ClassOperationEvent
__ClassCreationEvent                                        __ClassDeletionEvent
__ClassModificationEvent                                    __InstanceOperationEvent
__InstanceCreationEvent                                     __InstanceDeletionEvent
__InstanceModificationEvent                                 __TimerEvent
__AggregateEvent                                            __EventConsumer
__EventFilter                                               __FilterToConsumerBinding
__EventGenerator                                            __TimerInstruction
__AbsoluteTimerInstruction                                  __IntervalTimerInstruction
__TimerNextFiring                                           __SystemEvent
__EventDroppedEvent                                         __EventQueueOverflowEvent
__ConsumerFailureEvent                                      __SystemSecurity
CIM_ManagedSystemElement                                    CIM_LogicalElement
CIM_Service                                                 MicrosoftDNS_Server
MicrosoftDNS_Domain                                         MicrosoftDNS_Zone
MicrosoftDNS_Cache                                          MicrosoftDNS_RootHints
MicrosoftDNS_ResourceRecord                                 MicrosoftDNS_AType
MicrosoftDNS_SOAType                                        MicrosoftDNS_PTRType
MicrosoftDNS_NSType                                         MicrosoftDNS_CNAMEType
MicrosoftDNS_MBType                                         MicrosoftDNS_MDType
MicrosoftDNS_MFType                                         MicrosoftDNS_MGType
MicrosoftDNS_MRType                                         MicrosoftDNS_MINFOType
MicrosoftDNS_RPType                                         MicrosoftDNS_MXType
MicrosoftDNS_AFSDBType                                      MicrosoftDNS_RTType
MicrosoftDNS_HINFOType                                      MicrosoftDNS_ISDNType
MicrosoftDNS_TXTType                                        MicrosoftDNS_X25Type
MicrosoftDNS_WKSType                                        MicrosoftDNS_AAAAType
MicrosoftDNS_SRVType                                        MicrosoftDNS_ATMAType
MicrosoftDNS_WINSType                                       MicrosoftDNS_WINSRType
CIM_Component                                               MicrosoftDNS_ServerDomainContainment
MicrosoftDNS_DomainDomainContainment                        MicrosoftDNS_DomainResourceRecordContainment

from here, you could replace MicrosoftDNS_Zone class with MicrosoftDNS_ResourceRecord class etc.

Have fun!

Posted: Jul 15 2008, 08:11 PM by yli628 | with no comments
Filed under:
PowerShell Script to Put the Agent, the Health Service and the Health Service Watcher on the Agent into Maintenance Mode Revisited

This is an update version of my previous Post

I realize there are may be confusions regarding running OpsMgr related script in regular PowerShell console for some people. This script is for you to directly running from the command shell which comes with OpsMgr console;

I used computerPrincipalName in my previous post, which is FQDN, to save some typing, I use computername instead;

last but not least, I modified the script to work with multiple computers. Enjoy!

*********************************************************************

param($computerNames,$numberOfHoursInMaintenanceMode,$comment)

Foreach ($computerName in $ComputerNames)
{
$computer  = Get-Agent | Where-object {$_.ComputerName –eq $computerName}
$healthService = $computer.HostedHealthService
$healthServiceWatcherClass = get-monitoringclass -name:Microsoft.SystemCenter.HealthServiceWatcher
$healthServiceCriteria = "HealthServiceName='" + $computer.PrincipalName + "'"
$healthServiceWatcher = get-monitoringobject -monitoringclass:$healthServiceWatcherClass -criteria:$healthServiceCriteria
$startTime = [System.DateTime]::Now
$endTime = $startTime.AddHours($numberOfHoursInMaintenanceMode)

"Putting " + $computerName + " into maintenance mode"
New-MaintenanceWindow -startTime:$startTime -endTime:$endTime -monitoringObject:$computer.HostComputer -comment:$comment

"Putting the associated health service into maintenance mode"
New-MaintenanceWindow -startTime:$startTime -endTime:$endTime -monitoringObject:$healthService -comment:$comment

"Putting the associated health service watcher into maintenance mode"
New-MaintenanceWindow -startTime:$startTime -endTime:$endTime -monitoringObject:$healthServiceWatcher -comment:$comment

#To confirm your result and the returned time is Universal Time

Get-MaintenanceWindow -MonitoringObject $computer.hostcomputer
}

*************************************************************************

Save the above script (Between the lines) as whatever.ps1

Start your command shell with your admin (for OpsMgr) account and type the following in the prompt

PS Monitoring:\XYZPMP01
>c:\MyWorkSpace\Whatever.ps1 (gc c:\MyWorkSpace\list.txt) 0.25 'UpdateXXX'

Your list.txt should look like this:

server1

server2

...

PowerShell Script to check OpsMgr Agents Service and HealthState

Here is a PowerShell script to check OpsMgr Agents Service and HealthState

You need to either run it in Operation Manager's own command shell or you can use regular PowerShell console as mentioned in my previous post Here

Below is what's in AddConnSCOMSnapin.ps1

Add-PSSnapin "Microsoft.EnterpriseManagement.OperationsManager.Client"
Set-Location "OperationsManagerMonitoring::"
$rootMS = "XYZOPMP01"
new-managementGroupConnection -ConnectionString:$rootMS
Set-Location $rootMS

PS C:\Documents and Settings\yl.admin\My Documents\PS> .\AddConnSCOMSnapin.ps1

PathName             :
ManagementGroup      : XYZ Enterprise Apps
ManagementServerName : XYZOPMP01
Drives               :

PS Microsoft.EnterpriseManagement.OperationsManager.Client\OperationsManagerMonitoring::XYZOPMP01> & "C:\Documents and Settings\yl.admin\My Documents\PS\CheckAgentHealth.ps1"

Below is the script - CheckAgentHealth.ps1

#Start

$erroractionpreference = "SilentlyContinue"

$a = New-Object -comobject Excel.Application
$a.visible = $True

$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)

$c.Cells.Item(1,1) = "Machine Name"
$c.Cells.Item(1,2) = "Ping Status"
$c.Cells.Item(1,3) = "Health Service Status"
$c.Cells.Item(1,4) = "Health State"

$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$d.EntireColumn.AutoFit($True)

$intRow = 2

#get all the agent managed servers from OpsMgr

$ColServers = get-agent

foreach ($strServer in $colServers)
{
$c.Cells.Item($intRow, 1) = $strServer.Computername.ToUpper()

# Ping each server

Function PingServer
{
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.send($strServer.Computername)
if ($Reply.status –eq “Success”)
{
$c.Cells.Item($intRow, 2) = “Online”
}
else
{
$c.Cells.Item($intRow, 2).Interior.ColorIndex = 3
$c.Cells.Item($intRow, 2) = "Offline"
}
}
PingServer

#Check if the HealthService is running

Function CheckHealthService
{
$HealthService = [System.ServiceProcess.ServiceController]::GetServices($strServer.Computername) | where{$_.name -eq 'HealthService'}
If ($HealthService.status -eq "Running")
{
$c.Cells.Item($intRow, 3) = "Running"
}
ElseIf($HealthService.Status -eq "Stopped")
{
$c.Cells.Item($intRow, 3).Interior.ColorIndex = 3
$c.Cells.Item($intRow, 3) = "Stopped"
#You can start the service here if you want to

#$HealthService.Start()
}
Else
{
$c.Cells.Item($intRow, 3).Interior.ColorIndex = 6
$c.Cells.Item($intRow, 3) = "Not Sure"
}
}
CheckHealthService

# get the HealthState of the agents

#(you will get a number: 0-uninitialized; 1-success; 2-warning; 3-errors)

$c.Cells.Item($intRow, 4) = $strServer.HealthState

$intRow = $intRow + 1

}
$d.EntireColumn.AutoFit()

#End

OpsMgr 2007 Web Console Remote Access - Unexpected Error

When I try to access my OpsMgr 2007 SP1 Web Console remotely as an regular user, I got the below error

Web Console Error

The Application Event log on my RMS/Web Console has the below error:

Event Type:    Warning
Event Source:    ASP.NET 2.0.50727.0
Event Category:    Web Event
Event ID:    1309
Date:        7/9/2008
Time:        6:25:38 PM
User:        N/A
Computer:    XYZOPMP01
Description:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 7/9/2008 6:25:38 PM
Event time (UTC): 7/9/2008 10:25:38 PM
Event ID: 8d511823028c45dcbf063fc4d3740b31
Event sequence: 882
Event occurrence: 57
Event detail code: 0
Application information:
    Application domain: /LM/W3SVC/2/ROOT-1-128601124183270585
    Trust level: Full
    Application Virtual Path: /
    Application Path: D:\Web Console\
    Machine name: XYZPMP01
Process information:
    Process ID: 55828
    Process name: w3wp.exe
    Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
    Exception type: UnauthorizedAccessMonitoringException
    Exception message: The user Domain\YLi does not have sufficient permission to perform the operation.
Request information:
    Request URL: http://xyzopmp01:51908/InternalPages/NavigationTree.aspx?SpaceId=1001&ViewId=
    Request path: /InternalPages/NavigationTree.aspx
    User host address: xxx.xxx.xxx.xxx
    User: Domain\YLi
    Is authenticated: True
    Authentication Type: Negotiate
    Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
    Thread ID: 10
    Thread account name: NT AUTHORITY\NETWORK SERVICE
    Is impersonating: False
    Stack trace:    at Microsoft.EnterpriseManagement.DataAbstractionLayer.SdkDataAbstractionLayer.HandleIndigoExceptions(Exception ex)
   at Microsoft.EnterpriseManagement.DataAbstractionLayer.TypeSpaceOperations.GetFoldersByCriteria(MonitoringFolderCriteria criteria, String languageCodes)
   at Microsoft.EnterpriseManagement.ManagementGroup.GetMonitoringFoldersInternal(MonitoringFolderCriteria criteria)
   at Microsoft.EnterpriseManagement.ManagementGroup.GetMonitoringFolders()
   at Microsoft.EnterpriseManagement.OperationsManager.DataAbstractionLayer.DataAbstraction.BuildTree(String rootName)
   at NavTreeHelper.BuildOperationsTree(IDataAbstraction OpsSdkWrapper)
   at NavTreeHelper.BuildSpaceTree(IDataAbstraction OpsSdkWrapper, WunderbarSpace selectedSpace)
   at NavigationTree.Page_Load(Object sender, EventArgs e)
   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Web.UI.Control.OnLoad(EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Custom event details:

But I know my Web Console works and I can access it on RMS server and I also can access the Web Console remotely using my admin account. So this is definitely a permission issue. I tried to follow some of the post - added my regular user account to Performance Monitor Users group on RMS - no luck!

Finally I added my regular user account to Read-Only Operator group in OpsMgr - Those errors are gone and I can access web console remotely with my regular account!

You would think this is a no brainier but it indeed gets me stuck and also I see some other people has the similar issue Here

So if you run into the above issue, make sure the user account has at least Read-Only Operator role!

Posted: Jul 09 2008, 08:10 PM by yli628 | with no comments
Filed under:
IIS7 PowerShell Provider CTP2 Released

Microsoft released PowerShell Provider CTP2 for IIS7 yesterday and you can download it Here

I just installed it on my Vista SP1 machine. It installs without issue (Require you turn on IIS7 and Windows Process Activation Service of course)

I played with it a few and here is how you find your way around

PS IIS:\> dir

Name
----
Sites
AppPools
SslBindings (this is new to CTP2)

PS IIS:\> cd sites
PS IIS:\Sites> dir

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
Default Web Site 1               %SystemDrive%\inetpub\wwwroot

PS IIS:\Sites> cd ..
PS IIS:\> cd apppools
PS IIS:\AppPools> dir

Name                     State        Applications
----                     -----        ------------
DefaultAppPool           Started      Default Web Site

PS IIS:\> get-command
Type: AppPools

CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Add-Content                     Add-Content [-Path] <String[...
Cmdlet          Add-History                     Add-History [[-InputObject] ...
Cmdlet          Add-Member                      Add-Member [-MemberType] <PS...
Cmdlet          Add-Module                      Add-Module [-Name] <String[]...
Cmdlet          Add-PSSnapin                    Add-PSSnapin [-Name] <String...
Cmdlet          Add-Type                        Add-Type [-TypeDefinition] <...
Cmdlet          Add-WebConfiguration            Add-WebConfiguration [-Filte...
Cmdlet          Add-WebConfigurationProperty    Add-WebConfigurationProperty...
Cmdlet          Backup-WebConfiguration         Backup-WebConfiguration [-Na

 

 

 

 

I wish I will have a production IIS7 environment soon so I could explore this further. I have a feeling it’s going to be very cool!

Posted: Jul 03 2008, 08:20 PM by yli628 | with no comments
Filed under:
PowerShell Summer Olympics

Quest is holding their Summer Olympics (PowerShell) not in Beijing but Here. You could get your hands dirty with PowerGUI and could potentially win anywhere from $250 to $500 gift certificates to Amazon .com!

Posted: Jul 02 2008, 07:43 PM by yli628 | with no comments
Filed under:
2008 Microsoft® MVP Award

Just got an email from Microsoft and I got the 2008 MVP Award in Admin Frameworks. This is the second year in a row! What a great independence day gift! Cheers!