Thursday, October 19, 2017

#OpsMgr: Bulk deployment of Linux agents via a script

One of my customers had a requirement to deploy in excess of 2000 Linux agents recently, and was looking for a streamlined way of doing this. I found a couple of scripts online that can help with the deployment of the agent, but none that did quite what we needed to do, so I wrote my own.

Pop the list of agents to deploy into a text file and update the script to point to that file. You can also specify the name of the resource pool that should manage these agents. The script will prompt you for the run-as account username and password when you run it, so this is probably not ready to run unattended.

Script pings agent first to make sure it is reachable, and will then attempt to deploy/configure the agent, the same way the discovery does in the console.

Script results are saved into a CSV file, which is also mailed to you.

Update the bits highlighted in yellow before running. I would also recommend doing to pasting via notepad thing to ensure no mangling of quotation marks, etc happen.


#################################################################
#
#   SCOM-Linux-Agent-Discovery-script.ps1
#
#   Script by: Vanessa Bruwer
#
#
#    This script initiates the discovery for a list of Linux servers from a text file.
#    It is to be used for a set of servers to be managed by the Resource Pool
#    specified in this script.
#
#    The script does some prechecking before the server is added to the discovery.
#
#    It is based on the script provided by Operating Quadrant here:
#    https://operatingquadrant.com/2012/12/06/using-powershell-for-automated-unixlinux-agent-discovery/
#
#################################################################

# Parameters

$UserName = Read-Host -Prompt 'Please enter the Linux username'
$Password = Read-Host -Prompt 'Please enter the Linux password'


# Variables

$ResourcePoolName = "Linux Resource Pool"
$AgentFileLoc = "c:\temp\scripts\linuxagentlist.txt"

$sleeptime = "60"      # sleep time in seconds



$FromEmail = ""
$ToEmail = ""
$MailServer = ""


$ReportDate = Get-Date -format "yyyy-M-dd"

$rnd = Get-Random -minimum 1 -maximum 1000
$ReportLocation = "C:\Temp"
$ReportName = "$ReportDate-$rnd-SCOM-linuxagentdiscovery.csv"
$SavetoFile = "$ReportLocation\$ReportName"



# there should be no need to update the script beyond this point


# Delete any previous versions of the report for in case

If (Test-Path $SavetoFile){
     Remove-Item $SavetoFile
}

# Open the content
$body = @()

$body += "Server Name,Ping Response,DiscoveryResult"


# Read the text file
$Agents = get-content $AgentFileLoc


# Connect to Operations Manager

Import-module OperationsManager

$wsmanuser=$UserName
$wsmanpassword = ConvertTo-SecureString $Password -AsPlainText -Force


$WSCredential = New-Object System.Management.Automation.PSCredential ($wsmanuser, $wsmanpassword)
$Pool = Get-SCOMResourcePool -DisplayName $ResourcePoolName

$SSHCredential = Get-SCXSSHCredential -username $UserName –ElevationType sudo

# Set the counters to Zero
$i = 0
$n = 0

# Loop through the pending agents and ping them
foreach ($Agent in $Agents) {

$n = $n+1

   if (test-Connection -ComputerName $Agent -Count 2 -Quiet )
         {
     $Status = "Responds"

    $DiscResult = Invoke-SCXDiscovery -name $Agent -ResourcePool $Pool -WsManCredential $WSCredential -SshCredential $SSHcredential

    $DiscResult | fl Succeeded, ErrorData
     $DiscResult | Install-scxagent

if ($DiscResult.Succeeded){

$DiscStatus = "Success"
}
elseif ($DiscResult.EndpointAlreadyManaged)
{
$DiscStatus = "Skipped, already managed"
}
elseif ($DiscResult.ErrorData){
$DiscStatus = "Error occurred, please investigate"
}


Start-Sleep -s $sleeptime

         }
          else
          {
       $Status = "Unreachable"
       $i = $i+1

      $DiscStatus = "Skipped"
          }


# Write to the report
$ReportOutput = "$Agent,$Status,$DiscStatus"
$body += $ReportOutput
}


$agentcnt = $n-$i

$body >> $SavetoFile

$mbody = "There are $n Linux agents in the text file, $i not pinging and $agentcnt added to discovery"

Write-Host "There are $n Linux agents in the text file, $i not pinging and $agentcnt added to discovery"

Write-Host “Sending Email”


  #Creating a Mail object
      $msg = new-object Net.Mail.MailMessage
      $att = New-Object Net.Mail.Attachment($SavetoFile)

#Creating SMTP server object
      $smtp = new-object Net.Mail.SmtpClient($mailserver)

#Email structure
  $Subject = "SCOM Linux Agent discovery - $ReportDate"

     $msg.From = $FromEmail
      $msg.ReplyTo = $FromEmail
      $msg.To.Add($ToEmail)
      $msg.subject = $Subject
      $msg.body = $mbody
      $msg.Attachments.Add($att)


   #Sending email
     $smtp.Send($msg)

#write-host "Email sent"


And, as always, test in lab before using in production.

Thursday, September 28, 2017

SCSM Unsealed MP backups

I have now also created an updated version of the unsealed MP backup script that works with System Center Service Manager.

You can use this one to schedule your unsealed MP backups on a regular basis. Just update the location of the backup folder (highlighted), save as a .ps1 file and go.

Have tested on SCSM 2012 and SCSM 2016

##############################################################################
#
#   SCSM-UnsealedMP-Backup.ps1
#
#    This script backs up all unsealed management packs to a folder with the backup date as folder name
#
##############################################################################

# Variables

$ReportDate = Get-Date -format "yyyy-M-dd"
$path = "c:\Backups\$ReportDate\"


# there should be no need to update the script beyond this point

# test if the folder exists, and, if not, create it

If (!(Test-Path $path)){
     New-Item -ItemType directory -Path $path
}

# Connect to Service Manager

# Service Manager Administrator Module
$InstallationConfigKey = 'HKLM:\SOFTWARE\Microsoft\System Center\2010\Service Manager\Setup'
$AdminModule = (Get-ItemProperty -Path $InstallationConfigKey -Name InstallDirectory).InstallDirectory + "Powershell\System.Center.Service.Manager.psd1"
Import-Module -Name $AdminModule

#Connect to management server
$ServerConfigKey = 'HKCU:\Software\Microsoft\System Center\2010\Service Manager\Console\User Settings'
$SvcMgmtSrv = (Get-ItemProperty -Path $ServerConfigKey).SDKServiceMachine
New-SCManagementGroupConnection -ComputerName $SvcMgmtSrv


# get all the unsealed management packs and create array

$MPS = Get-SCManagementPack | where {$_.Sealed -eq $false}

# step through the management packs and export them to the folder specified
foreach($mp in $mps)
{
export-SCManagementpack -managementpack $mp -path $path
}



And thanks goes to Matthew Dowst for simplifying the SCSM module loading.

Thursday, September 21, 2017

OpsMgr 2016: Issue with Scheduled Maintenance Mode

I ran into an issue at a customer recently where they were unable to use the scheduled maintenance mode function in the console. When trying to save the schedule, they would receive the following error:

maintenancemodeerror

The error text contains the following:

Microsoft.EnterpriseManagement.Common.ServerDisconnectedException: The client has been disconnected from the server. Please call ManagementGroup.Reconnect() to reestablish the connection. ---> System.ServiceModel.CommunicationObjectFaultedException: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.


The fix is simple:

Grant sysadmin permissions to the SDK account on the SQL Instance hosting the OperationsManager database.

If you are unable to grant SA rights to this account, you can assign the following rights on the MSDB database:

  • SQLAgentOperatorRole
  • SQLAgentReaderRole
  • SQLAgentUserRole

There is no need to restart services or the console, the fix will work instantly.

Friday, July 21, 2017

Automatically add entries to a SharePoint calendar

I created a pretty cool script today to prebook slots in a SharePoint calendar.

This could be handy if you want to use a SharePoint calendar for a booking system, like appointments or room bookings.


#################################################################
#
#
#     Sharepoint-AddCalendarBookings.ps1
#
#
#     This script will add a set of calendar entries to a sharepoint calendar
#     with a status of Free. The intention is to use this calendar as a booking system
#     for appointments
#
#     It will, by default, add it for next month. Change the addmonths variable to
#     a bigger number to affect a different month in the future (next month = this month + 1)
#
#     It will, by default, book 15 minute slots. Change the $a variable to increase this value
#
#################################################################

#Variables
$webURL = "http://sharepointwebsiteaddresshere" 
$listName = "ListNamehere" 

$addmonths = 3 # number of months to add to calculation

$a = 15 # duration of the appointment

$StartTime = "09:00:00" # time of first appointment
$NumAppt = "27" # number of appt for day (9-4 is 8 hours, 8*60/15 = 28, less one slot is 27) if you change length of appt you will need to change this value

# end of variables

# there should be no need to update the script beyond this point


#Add SharePoint PowerShell Snapin which adds SharePoint specific cmdlets 
Add-PSSnapin Microsoft.SharePoint.PowerShell
  
#Get the SPWeb object and save it to a variable 
$web = Get-SPWeb $webURL 

#Get the SPList object to retrieve the "Demo List" 
$list = $web.Lists[$listName]

# get today's date
$today = get-date

# get next month
$nextmonth = $today.AddMonths($addmonths)

# get the month and year value for next month
$month = ($nextmonth).Month
$year = ($nextmonth).Year


# now get the number of days in the month

$eom  = [datetime]::DaysInMonth($year,$month)


# now, lets loop through the number of days in the month
foreach ($n in 1..$eom) {

$date = get-date "$month/$n/$year $StartTime"

$day = ($date).DayOfWeek.value__

# make sure we don't book week-ends
if ($day -ne 0 -and $day -ne 6){

foreach ($q in 0..$NumAppt) {
   $i = $a*$q

$timeslot = (get-date $date).AddMinutes($i)


#Create a new item 
$newItem = $list.Items.Add() 
 
#Add properties to this list item 
$newItem["Title"] = "Appointment Open Slot"
$newItem["Category"] = "Appointment"
$newItem["Start Time"] = $timeslot
$newItem["End Time"] = ($timeslot).AddMinutes($a)
$newItem["Status"] = "Free"

 
#Update the object so it gets saved to the list 
$newItem.Update() 

write-host "Entry added for $timeslot"

}

}

}


I’ve been helping a customer build a booking system for one of their processes using Service Manager, Orchestrator and Sharepoint, which is why this script was born.

Friday, July 7, 2017

Orchestrator connector doesn’t sync in #SCSM

I ran into an issue today with an Orchestrator connector that just would not sync in Service Manager, and event 26319 being logged in the Operations Manager event log on the SCSM Management Server.

This is what the event looks like:

Capture-scsm1

All services were started, could open the Orchestrator web service URL from the SCSM server, and nothing seemed out of order.

Quick restart of the Microsoft Monitoring Agent on the SCSM MS fixed the issue.

Related Posts with Thumbnails