## Tag Archives: PowerShell

### SCSM 2012: Asset Management Part 6 – Runbook/Automation details

This is the sixth and last part of the blog series about my Asset Management solution for SCSM 2012 R2.
Part 1: General overview
Part 2: Authoring – Classes and Relationships
Part 3: Folders and Views
Part 4: Authoring – Forms
Part 5: Reports

This part of the series covers the runbooks which are created with System Center Orchestrator 2012 R2.

All Orchestrator Runbook servers need the following software and Integration Packs installed:

Nearly all runbooks use the SCSMServer variable, which you need to set:

There are three main runbooks. All check the status of Windows Computers and create or update assets. All three inform site owners at the end through email. These activities also need adjustment as you need to enter the SMTP server information and email addresses.

You can read this blog to understand the dependency between the Windows Computer object and the Deployed Computer object from SCCM. There you also see that some information, which we need to create the asset, is in the Deployed Computer object (as the serial number).

1.Create assets:

This is the main runbook to create the computer assets. It checks if the asset for a deployed Windows Computer exists, if it exists, then it only checks the relationship and updates the asset. If it does not exist, then it gets the required information through the sub runbooks and then creates the asset and the necessary relationships.

2. Update assets:

This runbook only updates the location information, if the asset was re-imaged at a new site.

3. Check deleted:

This runbook only checks for deleted objects, but does not delete the asset, as it should stay in the database.

The following sub runbooks get additional information for the assets.

Get Location information:

This runbook checks if the list entries exist for the country and site and if they are new, then it creates the enum list entry.

This runbook in the “Get Location Info” activity checks a local text file, which has the site information in this format Shortname – Site – Country – Region. Example: FRA – Frankfurt – Germany – Europe. You can also query that information from a database if you have it there.

In the “Check Country/Site” activity it checks if the enum value exists and if not, then it creates it. You will need to check, if you have another GUID for your enum lists:

$CountryEnum=’c94c8568-8cc8-2f32-ec3a-8b8b04cc9848′$SiteEnum=’9d07bd6a-9e08-439e-486c-4ba4e7f88b30′

Check Model/Manufacturer:

This runbook checks if the list entries exist for the model and manufacturer and if they are new, then it creates the enum list entry.

You will need to check, if you have another GUID for your enum lists:

$ManufacturerEnum=’6e131742-a95b-6143-05c8-ee0f1aabae06′$ModelEnum=’457cb61d-0c0c-7229-62ef-7b343f7b7941′

Get Warranty information: Find detailed information in this post.

Create AssetToComputerAsset Relationship:

Create AssetCustodian Relationship:

Check Relationships:

Additionally we have this runbook, which checks the relationships for all classes to the AssetManagementBase class and creates them, if they do not exist.

These runbooks all only check the Windows Computer objects. If you have another source which you can use to create/update other asset object types, then you can create your own runbooks for it.

Have fun!

### SCOM: Sample Maintenance Mode MP works on SCOM 2016

With all the great changes related to Maintenance Mode in SCOM 2016 you probably only miss the possibility to easily set Maintenance Mode on the agent without the need of knowing the PowerShell script details.

My old Sample Maintenance Mode management pack can help you with this also on SCOM 2016. I have imported it into my SCOM 2016 test environment and set a server into maintenance mode through it without any problem.

It was required in the past, that you deploy the files separately to the agents to have the Splash Screen available. Now I have added the files to the Visual Studio solution and deploy them to c:\it\mom\mm. The solution also adds a shortcut to the default user desktop and to the public startup folder on Windows Server 2012 and above (also applies to the corresponding client versions). I have used the examples from David Allen’s blog post.

I have posted the sample sealed mpb file on github including also the whole solution.

To adjust the solution to your needs I recommend to change the text in the file OpsMgrMM.ps1 which runs the Splash Screen.
Also you can change the target directory in the DeployableFile.ps1:

$TargetDirectory = “C:\IT\MOM\MM” You will find both files in the Resources folder. When you have done your adjustments, then build the solution (seal the mps) and import the mpb file into your SCOM environment. If you had a previous version installed, then you will need to remove that first. Have fun with it! ### SCOR 2012: Monitor expired CA certificates A lot people might think, why should I monitor expiring certificates with System Center Orchestrator 2012. There are already solutions to monitor certificates in the local store on Windows computers – for example the wonderful solution from Raphael Burri (PKI Certificate Verification MP). But we had an issue with an expired certificate on non-windows systems. With that problem the idea came up to directly query expired certificates from the certificate authority (CA) – our internal cert store. We also wanted to notify the requesters directly, when a certificate expires within the next 30 days, send him/her reminders and last but not least inform the management a few days before the certificate expires, if no one has taken an action. With that idea we through about an automation solution – System Center Orchestrator. Here is the description of the solution. Prerequisites: • System Center Orchestrator 2012 R2 • Exchange Mailbox to send and receive emails and a user which has permissions to it • Exchange Users Integration Pack • PS PKI PowerShell module installed on all Runbook servers • Microsoft Certification Authority • SQL Temp database (Orchestrator Temp) Temp Database config: Mailbox folders: Exchange Users Integration Pack Config: GetEmail: Move Email: For both configurations you need to know the path of your Exchange Server EWS service: https://autodiscover.fqdn/EWS/Exchange.asmx and the user with domain and password, which owns the mailbox. After importing the runbooks, you will also need to configure the SQL activites (enter DB instance and Database) and the Send email activities (SMTP server and addresses). There will be some more things to change, but I will mention them in the runbook descriptions. I suggest to run the runbooks through a scheduled task on a daily basis. The first runbook reads the certificates and writes them to the database: Certificates.WriteToDB Update the template list, you want to check, in the GetCerts Activity:$Templist=@(
“WebServer”, #Web Server
“1.3.6.1.4.1.311.21.8.15817755.12287325.10963384.6580300.14252506.110.2574398.13148790” #Web Servers
)

Enter the names of the CAs which should be checked:
$canames=@(‘CA1FQDN‘,’CA2FQDN‘) Certificates.GetRequesterEmail Update the domain names and FQDNs which should be checked in the Get Requester Email activity. function get-domain($dn)
{
if($dn -like “*,dc=domainshortname1*”){$domain = “domain1fqdn“}
if($dn -like “*,dc=domainshortname2*”){$domain = “domain2fqdn“}
return $domain } Now that we have all expiring certificates in the database, we need a runbook, which sends out the notifications. Certificates.Notifications The first email will be send out when 30 days are left and it should be send to the service desk to create a ticket. The requester will be on CC. The second email is send to the requester from day 29 to day 4. And then the last emails will be send to the management and the requester as CC. We also created two additional runbooks to update the requester, if this information is not current anymore or to stop the notifications, if the certificate is already extended. The requester has the option in his emails to click on a link which creates a new pre-filled email for both situations. If the certificate PPR changed, then he/she should enter the email address of the new PPR into the CC field and send the email. If the certificate was extended, then he/she only needs to send the email. The emails will be sent to the mailbox for which we configured the Exchange User IP before. Information:Certificate extended email Information:Change certificate PPR email Certificates.UpdateRequesterEmail This runbook takes the email address of the CC field and writes it to the database, then it moves the email to the Certificates.NewRequester folder in the mailbox. Certificates.SetDeleted This runbook only sets a field in the database to deleted for the mentioned certificate in the email. Then it moves the email to the Certificates.Finished folder in the mailbox. This is the whole solution. You can download it from github. Most of the activities are PowerShell activities, so it should not be a big effort to also migrate the runbooks to Azure Automation or SMA. ### Getting Dell Warranty information If your company has Dell computers, then it could be necessary that you get the warranty information into your Asset Management System, for example: System Center Service Manager or even System Center Configuration Manager. There was a solution in the past to get this information directly through a REST api from a dell webpage, but that services was disposed in May 2016. Perhaps you already used one of these Solutions: Dell now offers a new way to get this information through the Dell Warranty Status API. Ok, that provides more security, but… The problem with this is, that every company needs to request access and go through an approval process: • Request access and provide information about your environment and the tool which should grab the data incl. throughput estimates • Then you get a key and the access to the sandbox system, where you test the connection. The key expires after 90 days. • After giving feedback and some more reviews, you will get the approval to use the production webpage with the same key. Until that you are allowed to use the sandbox system. More details can be found here. You can request the access here. I have created a PowerShell script which gets the ServiceLevelDescription and the EndDate for one Dell Computer. You can download the script here. #=========================================================================================== # AUTHOR: Natascia Heil # Script Name: GetDellWarrantyInfo.ps1 # DATE: 09/09/2016 # Version: 1.0 # COMMENT: – Script to check Warranty information for a computer from the # Dell Warranty Status API # Example: .\GetDellWarrantyInfo.ps1 -ServiceTag ‘1a2b3c’ -ApiKey “sdfj7122394057sdfiouwer” -Dev$true
#===========================================================================================
Param(
[Parameter(Mandatory=$true)] [String]$ServiceTag,
[Parameter(Mandatory=$true)] [String]$ApiKey,
[Parameter(Mandatory=$true)] [Bool]$Dev
)
#Build URL
If ($Dev) {$URL1 = “https://sandbox.api.dell.com/support/assetinfo/v4/getassetwarranty/$ServiceTag&#8221; } else {$URL1 = “https://api.dell.com/support/assetinfo/v4/getassetwarranty/$ServiceTag&#8221; }$URL2 = “?apikey=$Apikey”$URL = $URL1 +$URL2
# Get Data
$Request = Invoke-RestMethod -URI$URL -Method GET -contenttype ‘Application/xml’
# Extract Warranty Info
$Warranty=$Request.AssetWarrantyDTO.AssetWarrantyResponse.AssetWarrantyResponse.AssetEntitlementData.AssetEntitlement|where ServiceLevelDescription -NE ‘Dell Digitial Delivery’
# Read first entry if available
If ($Warranty -is [Object]) {$SLA=$Warranty[0].ServiceLevelDescription$EndDate=$Warranty[0].EndDate } else {$SLA=’Expired’
}

Here are two examples what information you can get through the API:

You can use this script in an Orchstrator Runbook or Azure Automation to feed data into i.e. SCSM.

Orchestrator Runbook example:

In the Initialize Data create a Parameter for the ServiceTag (Serialnumber of the machine).

In the Run .Net activity paste the PowerShell script, then you do not need the param part, you can directly enter the variables ($ServiceTag,$Apikey, $Dev) with the corresponding values. Enter$SLA and $EndDate as Published Data and define that as returned data of the Runbook. With that you can call this runbook from all other main runbooks and get the warranty data for a Computer. ### SCOM 2012: Get Pool Member monitoring details I recently had a problem that a custom rule was not running correctly, so I wanted to find out which of my SCOM 2012 Management Servers was running the All Management Servers Resource Pool instance, where the rule was targetted to. I could not find a something which matched in the web so I contacted some of my great SCOM colleagues and got feedback from Kevin Holman with the correct solution. Thanks Kevin! There are two tasks in SCOM already, which can give you more deatils about which Management Server takes care of which instance (class). I I will show now where you find them and what you need to enter. Both tasks you require the ID of the resource pool which handles the instances. In my case it is the ‘All Management Servers Resource Pool’. To find that run the Operations Manager Shell and enter the command: Get-SCOMResourcePool | FT Displayname, ID The output shows the resource pool names and the IDs. So copy the ID of the pool you need. Then go to your Operations Manager Console. Open the Management Servers State Dashboard view: Select one of the Management Servers in the Management Server State section. Then run the task ‘Get the Pool Member Monitoring a Top Level Instance’. Here you need to override the PoolId and the ManagedEntityID. In my case the IDs are both the same as I want to know which pool member of the All Management Servers Resource Pool manages the pool. In your case you perhaps want to know that for another class. You can find the ManagedEntityID of the class through the PowerShell command: (Get-SCOMClass -Displayname ‘xxx’).Id. The output of the Task gives you the Management Server Name: The second task has another approach. It gives you all top level instances which a Pool Member monitors. So run the ‘Get Top Level Instances Monitored by a Pool Member’ task. Here you only need to override the PoolId. The output lists all classes monitored by the pool member you selected in the Management Server State view. With that information you can now go on and troubleshoot the logs why things are not working correctly on that Management Server. ### SCOM 2012: OperationsManager module not found after WMF update I recently had the situation in my System Center Operations Manager 2012 SP1 environment that Windows Management Framework was updated on all of the management servers. At first sight everything looked good. At second sight I recognized that one management server had a problem. It was running a PowerShell script to set custom properties on alerts and this script did not find any alerts anymore. During investigation I found this error: import-module : The specified module ‘OperationsManager’ was not loaded because no valid module file was found in any module directory. I checked the PowerShell module directory, the module was there, but I couldn’t call it. I ifxed it by running a repair of the SCOM console installation. • Go to Control Panel • Select Programs: Programs and Features • Select System Center 2012 – Operations Manager and click Uninstall/Change • Select Repair the Operations Manager Installation • Select Operations console • Click Repair Additionally I recommend to reinstall the latest Update Rollup for the console again. ### PowerShell: Temperature monitoring If you want to monitor the temperature of your server rooms, then you have a lot of options. One is a temperature module, which is directly connected to your network and where you can access the temperature value through a XML file like: http://moduleIP/state.xml. We have used a solution from ControlByWeb, a PoE module with one sensor. The idea is to have a System Center Orchestrator runbook, which checks the temperature of all sensors and creates a SCOM alert when the temperature is higher than the threshold of 30°C. Then we also wanted to have a view directly in SCOM with the current values for all sensors. I used the PowerShell Web Widget for this. The main part for all of this is a PowerShell script. You can even use parts of the script and collect the data in SCOM. But herefore you will need one rule for each sensor. Functionality description: The script reads a text file from a share with all IP addresses and names of the temperature modules. Example: 192.168.10.110, Frankfurt 192.168.10.111, Paris Then it connects to each module, loads the state.xml and reads the value of the first sensor. With that data it creates an HTML table and writes that to a HTML file in a share on a web server. The last step is that it can load the web page in the PowerShell Web Widget. You can download the script on TechNet Gallery. ### SCCM 2012: Install downloaded Software Update through PowerShell With the last Patch cycle from Microsoft we had a bigger problem with the patch MS15-018, which failed on a lot of servers. The patch also prevented all other following patches to be installed. It was downloaded correctly, but could only be installed manually by running the downloaded exe-file from the SCCM cache folder. To automate this a bit, my colleague Mihaly Kolozsi created a PowerShell script based on my design ideas. A big thank to him for borrowing me his brain and time ;-). You can download it here. ### SCOM 2012: Check greyed out agents Greyed out agents are can be a nightmare for a System Center Operations Manager admin. An agent gets greyed out if the Health Service is not communicating correctly with the Management Servers. Normally an alert should be created with the name “Health Service Heartbeat Failure” which indicates this status. But sometimes I see the situation that the alert was created, but also auto-resolved by the system after a while (because of an agent recovery etc.). The problem then is if the agent still stays in an unhealthy state but no new alert gets created. I see that from time to time if the agent is stuck or has resource problems. This situation needs to be solved quickly because during that time no monitoring on the agent side takes place. So how can this be resolved? I implemented this solution: The management servers already know which agents are greyed out, so I have created a rule which runs on the “All Management Servers Resource Pool” every 5 min (you can select another interval if you like). It checks which agents are greyed out but are not in maintenance mode and then checks for each agent if there is an open “Health Service Heartbeat Failure” alert. It adds the server to a list which will be populated in one alert with the name “Sample – greyed out agents”, if no alert was found. The main logic of the rule bases on a Powershell script. Here is the part, with the logic – I have skipped everything around it (log function, SCOM module, etc.).$TotalCount=0
$list=””$agentclass = Get-SCOMClass -Name “Microsoft.SystemCenter.Agent”
# Find greyed out agents which are not in maintenance mode
$agentobjects = Get-SCOMMonitoringObject -Class:$agentclass | Where-Object {($_.IsAvailable -eq$false) -and ($_.InMaintenanceMode -eq$False)}
if ($agentobjects -is [Object]) {$msg = “rnFound greyed out agents which are not in maintenance mode.”;
Log -msg $msg -debug$debug -debugLog $debugLog; # Go through agent list foreach ($agent in $agentobjects) {$msg =  “rn”+ $agent.displayname Log -msg$msg -debug $debug -debugLog$debugLog;
#Go on if watcher state for the agent is unhealthy
if((Get-SCOMClass -name “Microsoft.SystemCenter.HealthServiceWatcher”| get-scomclassinstance |  Where-Object {$_.Displayname -eq$agent.DisplayName}).HealthState -ne ‘Success’)
{
# Find open Health Service Heartbeat Failure alert for the agent
$alert=get-scomalert -name ‘Health Service Heartbeat Failure’ | where {($_.ResolutionState -ne 255) -and ($_.MonitoringObjectDisplayName -eq$agent.DisplayName)}
# No alert for greyed out agent found
if ($alert -isnot [Object]) {$list+=”rn”+$agent.displayname$msg=”rnThe agent “+ $agent.displayname + ” has no open Health Service Heartbeat Failure alerts. Add to list.” Log -msg$msg -debug $debug -debugLog$debugLog;
$Totalcount++ } } } } You can find the rule in a small management pack called Sample.BaseMonitoring, which you can download here. It is designed for SCOM 2012 SP1. Please test it in your development environment before you add it to production! ### SCCM 2012: Get expired Advertisements There are some clean up tasks a System Center Configuration Manager 2012 Administrator can perform on a regular basis. One should be to check which advertisements are expired. Yes, I talk about advertisements in SCCM 2012. I know SCCM 2012 talks about deployments, but if you deploy a Package in SCCM (not an Application) then SCCM internally stores this deployment in the WMI class SMS_Advertisement. See also. There is no PowerShell Cmdlet for SCCM 2012 SP1 which could give me this information directly, so I have created a script, that can be used in two ways: 1. document which deployments are expired (only does not document the current assigned schedule) in a CSV format. 2. delete the expired deployments. So you can call the script with different parameters. Command line: Getexpiredadvertisements.ps1 -log [String] -sitecode [String] -siteserver [String] -document [Bool] -delete [Bool] Example: Getexpiredadvertisements.ps1 -log “c:\it\expiredads.csv” -sitecode “ABC:” -siteserver “SCCM01” -document$True -delete $False Possible Parameters: • Log: Defines name and path of the written CSV file • Sitecode: SCCM Site Code, Example ABC: • Siteserver: SCCM Site Server Name • Document: Defines, if expired Advertisements get documented to the CSV file, possible values:$True/$False • Delete: Defines, if expired Advertisements get deleted in SCCM, possible values:$True/\$False

Requirements:

• Run this script in PowerShell x86
• The script is tested with PowerShell 2.0 and SCCM 2012 SP1