Posts Tagged ‘Powershell’

So, here is the scenario, we managed a lot of customer’s System Centre Operations Manager (SCOM) environments. One of the most common issues we run into, it is the “Grey Agent” issue, where an agent is no longer reporting into SCOM. There might be a few reasons for this, however one of the most common and effective ways to fix this to clear the agent cache. By this, we simply mean connecting to the agent, stopping the “SCOM” service, deleting the content of the “Health Service State” folder and then restarting the “SCOM” service.

Yes, this is a perfect candidate for PowerShell and their a quite a few scripts that do this in numerous ways using PowerShell, I have a script for this, but they are usually dependant upon a list of some and then loop through this, I decided to use my friend, System Centre Orchestrator (SCO) to facilitate this is in a time manner, with more flexibility and log building as well as inputting the results into a database. With SCO, we also have more avenues available to us for error handling, like logging a call within SCSM or “richer” email or the like.

So, I have learnt with SCO, the best thing to do is to actually sit down and whiteboard you solution, simply draw out the steps you want to follow and think of some error handling. With my example, my logic was as follows. I have added a VIsio diagram as my handwriting is barely legible even to me 🙂

1. Query Database for grey agents, there is a SQL Script for this.

2. Create Folder for logging

3. Read SQL results into a file for “’looping”

4. DNS Test

5. Ping Test

6. Determine Service Name and folder path (Remember we might be dealing with multiple versions of SCOM here

7. Check Service status, to determine if a stop of the service is needed

8. Stop if needed

9. Delete files

10. Wait 10 Seconds

11. Start Service

12. Write log to Database


The SQL query will be part of the Runbook file, it can be found here, please change the extension to .ois_export.

Have fun automating.

(E-Mail me)

Follow me,

Twitter (Personal & System Centre)

Twitter (System Centre Focused)

Hi All,

It has been a little while, i have been quite involved with an Integration Project. With this project there was a requirement to add comments to a Work Item. The information is passed on from “System A” to “System B” via XML. Using PowerShell, extracting the XML contents is not too difficult, if anyone would like to dive into that a little bit, please let me know with Comments.

I decided not to re-invent the wheel, so some searching was in order, and I found the following post, this post gave the basics. However every time I tried to add additional comments, the comments were over-written and NOT replaced. Not quite the desired effect. So after some more checking and research and tinkering within the Service Manager, I discovered the following about comments.

When adding a Comment, there is adding of a relationship class, already mentioned in this post, however it also uses a GUID.


There is also another trick to adding comments within Orchestrator, this is discovered by trying to add a comment and then pulling all the available fields and looking at them. It is a small component which can be easily missed. The “Display Name” must also be the same GUID. So you might be asking how do we get the GUID?

Well, PowerShell can easily handle this for you.

$guid = [System.Guid]::NewGuid().ToString()

You simply use this a pre-cursor step and publish this data from “Run .Net Script”, so a sample would look like this.


Get-Object Properties

I pass on the ID Value I want to modify from another Runbook


Create Related Object Properties

I use an “Extended” class of comments needed for this project, principal remains the same.


I hope this saves  you some time and add some value.


(E-Mail me)


Follow me,


Twitter (Personal & System Centre)

 Twitter (System Centre Focused)

So recently, I had a customer ask me for the following as their previous incident management system had this functionality.

The customer wanted to be able to send an “Update Email” to a 3rd party from the SCSM Console with automatically placing the reference number into said email. They needed the functionality of sending to any email address. This was a requirement for the type of business they are in.

Please remember that I am by no means a developer. I was thinking of using System Centre Orchestrator, however for this simple requirement, I thought that it might be overkill. I am sure that in time, as the requirements grows and/or changes, System Centre Orchestrator will become a better fit. For this solution, I turned to my friend, PowerShell

I simply wanted to provide a clean interface for the customer to use. I follow a strict rule of KISS (Keep It Straight and Simple). With the PowerShell script, I provide two input fields.

  1. Email address of user for update to go to
  2. Update to be sent to customer.

The screenshot of what the window looks like

All of this was built in PowerShell with some from Sapien PrimalForms Community Edition to assist with the GUI part. The GUI is fully functional and tested. “Send Update” is responsible for sending the update to the specified person and the “Cancel” simply closes the form nicely and allows you to continue as normal.

PowerShell Code Below (SendEmail – Technet Gallery Download)

#region Script Settings
#<ScriptSettings xmlns="">
#  <ScriptPackager>
#    <process>powershell.exe</process>
#    <arguments />
#    <extractdir>%TEMP%</extractdir>
#    <files />
#    <usedefaulticon>true</usedefaulticon>
#    <showinsystray>false</showinsystray>
#    <altcreds>false</altcreds>
#    <efs>true</efs>
#    <ntfs>true</ntfs>
#    <local>false</local>
#    <abortonfail>true</abortonfail>
#    <product />
#    <version></version>
#    <versionstring />
#    <comments />
#    <company />
#    <includeinterpreter>false</includeinterpreter>
#    <forcecomregistration>false</forcecomregistration>
#    <consolemode>false</consolemode>
#    <EnableChangelog>false</EnableChangelog>
#    <AutoBackup>false</AutoBackup>
#    <snapinforce>false</snapinforce>
#    <snapinshowprogress>false</snapinshowprogress>
#    <snapinautoadd>2</snapinautoadd>
#    <snapinpermanentpath />
#    <cpumode>1</cpumode>
#    <hidepsconsole>false</hidepsconsole>
#  </ScriptPackager>

Import-Module 'C:\Program Files\Common Files\SMLets\SMLets.psd1' -Force

 #Generated Form Function
function GenerateForm {
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 2013-11-14 09:08 AM
# Generated By: Fletcher

 #region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null

 #region Generated Form Objects
$SendUpdateForm = New-Object System.Windows.Forms.Form
$CancelButton = New-Object System.Windows.Forms.Button
$SendUpdateButton = New-Object System.Windows.Forms.Button
$UpdateTextBox = New-Object System.Windows.Forms.TextBox
$UpdateLabel = New-Object System.Windows.Forms.Label
$EmailToTextBox = New-Object System.Windows.Forms.TextBox
$EMailToLabel = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#Generated Event Script Blocks
#Provide Custom Code for events specified in PrimalForms.
        Write-Host "Send Update"
        $to = $EmailToTextBox.Text
        Write-Host $to
        $from = ""
        $emailbody = $UpdateTextBox.Text
$subject = @"
Update [ID]
$body = @"
        #$subject = "Update [ID]"
        #Write-Host $subject
        #Write-Host $body
        $smtpserver = ""
        #[string]$body = $UpdateTextBox.Text
        #$testcommand = "Send-MailMessage -To $to -From $from -Subject $messagencontent -Body '$body' -SmtpServer $smtpserver"
        Send-MailMessage -To $to -From $from -Subject $subject -Body $body -SmtpServer $smtpserver
        #Write-Host $testcommand


#TODO: Place custom script here

{#Correct the initial state of the form to prevent the .Net maximized form issue
    $SendUpdateForm.WindowState = $InitialFormWindowState

#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 323
$System_Drawing_Size.Width = 409
$SendUpdateForm.ClientSize = $System_Drawing_Size
$SendUpdateForm.DataBindings.DefaultDataSourceUpdateMode = 0
$SendUpdateForm.Name = "SendUpdateForm"
$SendUpdateForm.Text = "Send Update"

 $CancelButton.DataBindings.DefaultDataSourceUpdateMode = 0

 $System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 182
$System_Drawing_Point.Y = 264
$CancelButton.Location = $System_Drawing_Point
$CancelButton.Name = "CancelButton"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 124
$CancelButton.Size = $System_Drawing_Size
$CancelButton.TabIndex = 5
$CancelButton.Text = "Cancel"
$CancelButton.UseVisualStyleBackColor = $True


 $SendUpdateButton.DataBindings.DefaultDataSourceUpdateMode = 0

 $System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 35
$System_Drawing_Point.Y = 264
$SendUpdateButton.Location = $System_Drawing_Point
$SendUpdateButton.Name = "SendUpdateButton"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 116
$SendUpdateButton.Size = $System_Drawing_Size
$SendUpdateButton.TabIndex = 4
$SendUpdateButton.Text = "Send Update"
$SendUpdateButton.UseVisualStyleBackColor = $True


 $UpdateTextBox.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 35
$System_Drawing_Point.Y = 135
$UpdateTextBox.Location = $System_Drawing_Point
$UpdateTextBox.Multiline = $True
$UpdateTextBox.Name = "UpdateTextBox"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 103
$System_Drawing_Size.Width = 290
$UpdateTextBox.Size = $System_Drawing_Size
$UpdateTextBox.TabIndex = 3


 $UpdateLabel.DataBindings.DefaultDataSourceUpdateMode = 0

 $System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 35
$System_Drawing_Point.Y = 110
$UpdateLabel.Location = $System_Drawing_Point
$UpdateLabel.Name = "UpdateLabel"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 22
$System_Drawing_Size.Width = 359
$UpdateLabel.Size = $System_Drawing_Size
$UpdateLabel.TabIndex = 2
$UpdateLabel.Text = "Please enter the information to be sent to intended recipient:"


 $EmailToTextBox.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 35
$System_Drawing_Point.Y = 54
$EmailToTextBox.Location = $System_Drawing_Point
$EmailToTextBox.Name = "EmailToTextBox"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 290
$EmailToTextBox.Size = $System_Drawing_Size
$EmailToTextBox.TabIndex = 1


 $EMailToLabel.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 35
$System_Drawing_Point.Y = 27
$EMailToLabel.Location = $System_Drawing_Point
$EMailToLabel.Name = "EMailToLabel"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 439
$EMailToLabel.Size = $System_Drawing_Size
$EMailToLabel.TabIndex = 0
$EMailToLabel.Text = "Please enter the email address of the intended recipient:"


 #endregion Generated Form Code

 #Save the initial state of the form
$InitialFormWindowState = $SendUpdateForm.WindowState
#Init the OnLoad event to correct the initial state of the form
#Show the Form
$SendUpdateForm.ShowDialog()| Out-Null

 } #End Function

 #Call the Function


Ok, so that is the PowerShell side done. Now, it is time to create the console task. This is a fairly straight forward exercise. There are only a few tips I would like to share. I used a shared folder for the scripts and then mapped the console task to the shared folder. Netivia Consulting has a great idea as well, I will be changing to PowerShell Remoting soon, great idea!!!!!

I have configured the PowerShell script to use a parameter, the ID of the Work Item, this is very easy to configure and ensure that the parameter is passed on. See below.

You will see that I used the “Log in action log when this task is run”. That is where the Write-host in the PowerShell script becomes handy, the write-host lines are added to the Action Log.

Please feel free to use and modify to meet your needs.

(E-Mail me)

Follow me.

Facebook (Personal)

Twitter (Personal & System Centre)

Twitter (System Centre Focused)

So, I am quite a keen user of PowerShell and System Centre Orchestrator. Ok, so I recently had a request from a customer that went as follows “I need DPM to alert me when tapes are ready to  be taken off-site.”

DPM does not seen to have this functionality out of the box within the Graphical User Interface (GUI). All is NOT lost, Data Protection Manager has a PowerShell component and i was sure i could figure out a way to get this to work within PowerShell. Sure enough a solution in the form of PowerShell was found, so using this as a base, I modified the PowerShell script to suit my needs. It was also slightly modified to use with System Centre Orchestrator. The custoemr also wanted some colour and wanted the result formatted in HTML. primarily for reading purposes and auditing purposes. PowerShell code below and link here.

Import-Module DataProtectionManager
$date = Get-Date -Format "M-d-yyyy"
$path = "c:\DPMOffisteTapes\"
$filepath = $path + $date + ".html"
#creates the folder if it does not exist
New-Item -itemType file -Path $filepath
$AllLibraries = get-dpmlibrary 
$AllTapes = Get-Tape -DPMLibrary $AllLibraries
$offistereadytape = $AllTapes | Where-Object {$_.isoffsiteready -eq $true}
$a = "<style>"
$a = $a + "BODY{background-color:Green;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:GreenYellow}"
$a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:palegoldenrod}"
$a = $a + "</style>"
$offistereadytape | Select-object location, barcode , isoffsiteready|ConvertTo-Html -Head $a -Body "<H2>Offsite Ready Tapes</H2>" | out-file -FilePath $filepath

OK, so now we have the data in decent format.


So, with the more tapes that are ready, the more rows of data will be within the HTML.

Ok, so now we need to schedule the task. I know i could have used Task Scheduler and the like, however we have System Centre Orchestrator and with Service Management Automation available, more and more tasks will be automated. With this example, i decided to use Orchestrator.

So, I simply use a Monitor/Date Time to run the required activity at set intervals


I then run a DPM Script from the Data Protection Manager Integration Pack.



The filepath Variable is where the html (the full path to the html file) is written, this is especially helpful when sending the Email Message. (I know this can be done with send-mailmessage directly within the PowerShell code)


So there you have it, Some Orchestrator Magic with PowerShell and DPM.

(E-Mail me)

Follow me.

Facebook (Personal)

Twitter (Personal & System Centre)

Twitter (System Centre Focused)

So, one of the consultants in the company I work at came to me with a strange request.

The request from the customer he was helping was the following. They wanted a way to connect to all the switches within their environment and then run some commands against the switch after connecting to the switch on port 23. Once the connection has been made, then some commands are run to get the current running configuration. Then export this to a text file.

So I found a basic script here. I have since taken this and modified and extended the script. I have added an array for the IPs to be checked. I have also added some checking prior to running any commands. I have added some testing.

First, we test the connection and see if the device is responding to pings. If the device is responding to pings, then test and see if the device is configured for telnet. So basically I am looking to see if port 23 is open. If port 23 is not opened, a log file is updated with the IP Address. If the device is not responding to pings, a log file is updated stating the IP of the “non-responding” device.

As an addition to the script, the files are then added to an e-mail which is sent to whomever you want to add. As part of the email process, a check is done and if an error is thrown, there is more information presented in the console to point you in the correct direction.

## PowerShell: Script To Telnet To Remote Hosts And Run Commands Against Them With Output To A File ##
## Overview: Useful for Telnet connections to Cisco Switches and other devices. Can add additional command strings
## Usage Examples: Add your environment specific details into the parameters below, or include when calling the script:
## ./PowerShellTelnetRemoteSession.ps1 "" "23" "admin" "password" "term len 0" "en" "enablepassword" "show interface"
    #[string] $remoteHost = "", 
    #[int] $port = 23,
    [string] $username = "admin",
    [string] $password = "",
    #[string] $termlength = "term len 0", #Useful for older consoles that have line display limitations
    [string] $enable = "en", #Useful for appliances like Cisco switches that have an 'enable' command mode
    [string] $enablepassword = "",
    [string] $command1 = "show run", #You can add additional commands below here with additonal strings if you want
    [string] $command2 = " ",
    [string] $command3 = " ",
    [string] $command4 = " ",
    [string] $command5 = " ",
    [int] $commandDelay = 1000
[string] $output = ""
## Read output from a remote host
function GetOutput
  ## Create a buffer to receive the response
  $buffer = New-Object System.Byte[] 4096
  $encoding = New-Object System.Text.AsciiEncoding
  $outputBuffer = ""
  $foundMore = $false
  ## Read all the data available from the stream, writing it to the
  ## output buffer when done.
    ## Allow data to buffer for a bit
    Start-Sleep -m 1000
    ## Read what data is available
    $foundmore = $false
    $stream.ReadTimeout = 1000
        $read = $stream.Read($buffer, 0, 1024)
        if($read -gt 0)
          $foundmore = $true
          $outputBuffer += ($encoding.GetString($buffer, 0, $read))
      } catch { $foundMore = $false; $read = 0 }
    } while($read -gt 0)
  } while($foundmore)
function Main
    param ($ip,$port)
  ## Open the socket, and connect to the computer on the specified port
  Write-Host "Connecting to $ip on port $port"

  $socket = New-Object System.Net.Sockets.TcpClient($ip, $port)
  Write-Host "Connected. Press ^D followed by [ENTER] to exit.`n"
  $stream = $socket.GetStream()
  $writer = New-Object System.IO.StreamWriter $stream
    ## Receive the output that has buffered so far
    $SCRIPT:output += GetOutput
        Start-Sleep -m $commandDelay
        #Start-Sleep -m $commandDelay
        Start-Sleep -m $commandDelay
        Start-Sleep -m $commandDelay
        Start-Sleep -m $commandDelay
                $writer.WriteLine($command1) #Add additional entries below here for additional 'strings' you created above
        Start-Sleep -m $commandDelay
                $writer.WriteLine($command2) #Add additional entries below here for additional 'strings' you created above
                Start-Sleep -m $commandDelay
                $writer.WriteLine($command3) #Add additional entries below here for additional 'strings' you created above
                Start-Sleep -m $commandDelay
                $writer.WriteLine($command4) #Add additional entries below here for additional 'strings' you created above
                Start-Sleep -m $commandDelay
                $writer.WriteLine($command5) #Add additional entries below here for additional 'strings' you created above
        Start-Sleep -m $commandDelay
        $SCRIPT:output += GetOutput
  ## Close the streams

  #building file name
  $filename = "c:\switch\$ip - " + $timestamp + ".txt"
  $output | Out-File $filename  #Change this to suit your environment

#build the list of ips to be interegated 
$ips = "","",""

#building a file path
$timestamp = get-date -Format g | foreach {$_ -replace ":","."}

#building different file paths for different functions
$errortimestamp = Get-Date -Format o | foreach {$_ -replace ":", "."}
$errorfilename = "c:\switch\" + $timestamp + " - ERROR.txt"

#building different file paths for different functions
$blockedtimestamp = Get-Date -Format o | foreach {$_ -replace ":", "."}
$blockedfilename = "c:\switch\" + $timestamp + " - blocked.txt"

#looping through each ip in ip list
foreach ($ip in $ips)
    Write-host "Testing $ip"
    #test to see if device is responding to pings
	if (Test-Connection $ip -Quiet)
        #creating connection on port 23
		$t = New-Object Net.Sockets.TcpClient
		$t.Connect($ip, 23)

        #if it connects, runs the required function with the ip
		if ($t.Connected)
			. Main $ip "23"
        #script block for device responding to ping, but port 23 is NOT open
			$portblocked = "Port 23 on $ip is closed , You may need to contact your IT team to open it. "
            Add-Content $blockedfilename "`n$portblocked"
    #script block for NO RESPONSE
    	$errorfilename = "c:\switch\" + $timestamp + " - ERROR.txt" 
        Add-Content $errorfilename "`nCould not ping $ip" 

#displaying information on console
Write-Host "Build file list" -NoNewline
#getting file list to be emailed
$files = Get-ChildItem C:\Switch\ | Where {-NOT $_.PSIsContainer} | foreach {$_.fullname}
#pausing script
Start-Sleep 3
Write-Host "`t" [File List Built] -ForegroundColor "Green"

Write-Host "Sending Email" -NoNewline

#building checks for sending emails

#no error

#replace as needed
$to = "<to>"
$from = "<from>"
$smtpserver = "<smtpserver>"

    Send-MailMessage -Attachments $files -to $to -from $from -Subject "Network Config backup - $timestamp" -SmtpServer $smtpserver -ErrorAction Stop
    Write-Host "`t [Email Sent]" -ForegroundColor "Green"
    $ErrorMessage = $_.Exception.Message
    if ($ErrorMessage -ne $null)
        Write-Host "`t [Unable to send Mail]" -ForegroundColor "Red"
        Write-Host "There was an error: $ErrorMessage" -ForegroundColor "Yellow"

Start-Sleep 3
Write-Host "Removing Files" -NoNewline
$files | Remove-Item
Write-Host "`t [Files removed]" -ForegroundColor "Green"

(E-Mail me)

Follow me.

Facebook (Personal)

Twitter (Personal & System Centre)

Twitter (System Centre Focused)

I have found a great for load testing SCSM with Incidents. The script uses SMLets to generate Incidents and you can then gauge how your system would handle the load you are planning within your Production Environment.

I will not go into the detail of the script as this blog post does a great job of explaining it. SO this got me to thinking about other Load Testing you could perform. The most common Load Test is with Incidents. However, i decided that another good load test would be Service Requests. What is nice about this load test, is that it uses a Management Pack which I have included in this post. The Management Pack contains a Service Request Template with a Manual Activity added as the first Activity. This will allow you to test Service Requests and well as Activities, which would in turn, test any workflows or runbooks that you have configured.

For my environment, i have additional runbooks which are also triggered when Manual Activities are completed or when Review Activities are completed. So with this Load Test script it also test my runbooks and other workflows.

Remember, to set a different Implementer for the Manual Activity to allow the runbooks or workflows to be triggered off correctly. Remember, no Manual Activity Implementer or if the implementer has no email address, your emails will not be triggered correctly. Below, is a breakdown of the script I am using.


#SMLets is needed for the script to work
Import-Module SMlets

#the number of Service requests to be created
$SRCount = 10

#the delay between attempts
$delay = 10

# Display Start Time
$StartTime = get-date
Write-Host "Started"
Write-Host $StartTime
Write-Host "-------------------`n"
Write-Host "Creating Service Request"
Write-Host "-------------------"
$i =1

while ($i -le $SRCount)

#Variable / Class Setup
$srClass = Get-SCSMClass -name System.WorkItem.ServiceRequest$
$srprior = Get-SCSMEnumeration -Name ServiceRequestPriorityEnum.Medium
$srurg = Get-SCSMEnumeration -Name ServiceRequestUrgencyEnum.Medium
$ararea = get-SCSMEnumeration -Name ServiceRequestAreaEnum.Other

#building your own SR Title
$title = "Fletcher Load Testing $i - " + (get-date)

#Service Request Arguements
$srargs = @{
Title = $title;
Urgency = $srurg;
Priority = $srprior;
ID = “SR{0}”;
Area = $ararea;
Description = “Created by Script”

#Create Service Request
New-SCSMOBject -Class $srClass -PropertyHashtable $srargs

#Get Projection &amp; Object for Created Service Request
$srTypeProjection = Get-SCSMTypeProjection -name System.WorkItem.ServiceRequestProjection$
$SRProj = Get-scsmobjectprojection -ProjectionName $srTypeProjection.Name -filter “title -eq $title”

#Get Template
$template = Get-SCSMObjectTemplate -DisplayName "Load Test SR Template"

#Set Template
Set-SCSMObjectTemplate -Projection $SRProj -Template $template
$SR = Get-SCSMObject -Class (Get-SCSMClass -Name System.WorkItem.ServiceRequest$) -filter "Title -eq $title"
$SRName = $
$SRTitle = $SR.Title
Write-Host $SRName " - " $SRTitle

# Pause before creating next SR
Start-Sleep -s 5

#getting the above created Service Request
$ServiceRequestToUpdate = Get-SCSMObject -Class (Get-SCSMClass -Name System.WorkItem.ServiceRequest$) -Filter "Id -eq $SRName"

#get the Realted Child Manual Activity
$ChildActivities = (Get-SCSMRelationshipObject -BySource $ServiceRequestToUpdate | ?{$_.RelationshipID -eq "2DA498BE-0485-B2B2-D520-6EBD1698E61B"})

$get the ID Value
$MAIDToUpdate = $ChildActivities.targetobject.values[9].value

#getting the MA Class
$Class = Get-SCSMClass -Name System.WorkItem.Activity.ManualActivity

#getting the "Active" Status
$StatusActive = Get-SCSMEnumeration -name ActivityStatusEnum.Active

$Activity = Get-SCSMObject -Class $Class | ? {$_.ID -eq $MAIDToUpdate}

#setting MA to Active
Set-SCSMObject -SMObject $Activity -Property "Status" -Value $StatusActive

#showing current status
Write-host $MAIDToUpdate " is now " $StatusActive
$i +=1
Start-Sleep -s $delay

# Display End Time
Write-Host "_______________________`n"
$EndTime = get-date
Write-Host = "Finished"
Write-Host $EndTime
#End of Script

The script can also be downloaded from the Technet Gallery here.

(E-Mail me)

Follow me.

Facebook (Personal)

Twitter (Personal & System Centre)

Twitter (System Centre Focused)

So recently I got an e-mail to my newly setup e-mail address, for just this reason Smile,  from someone asking if I knew a way to do the following.


“I was trying to find a way to find all Incidents related to a specific person (assigned  to or affected user) using PowerShell”

So, I decided the best to answer this with a blog post as maybe there are other people out there asking the same question. This is a quick solution using


At this moment in time, this will address ONLY incidents. I will work on some code using


to reference work items. I will add the pieces of code as I go and explain the code.

First lets start by importing the required module, SMLets can be downloaded here

import-module smlets

I am running these commands on a computer that is NOT the Management Server. So I need to specify a computer name when I am running these commands. So, in the next line I create a


variable to make my life easier. If you are running these commands on the Management Server, you can remove the

-computername $computername

piece of code. Below is how I created this, please use the name of your Management Server

$computername = “name of your Management Server"

Ok, so now lets get all active incidents. I will run a PowerShell Command to get all Incidents that are NOT EQUAL to “Resolved” or “Closed”. This allows us to cover all other incident statuses you may have created. Notice the –ne operator.

$allincidents = Get-SCSMIncident -ComputerName $computername | Where-Object {$_.Status -ne "resolved" -and $_.status -ne "closed"}

So now we have all the incidents in an object, now what????

Personally, I choose to sort the information, enter


with Powershell. So, to elaborate a little further you can use


orGM” for short and “pipe” your variable to “GM” / Get-member

$allincidents | gm 


$allincidents | get-member 


Now you have a list of all the properties you can use. You can also go deeper into the ‘Members’ of the object. You can do the following as well

$allincidents.affecteduser | gm 

It is simply a case of playing around and digging a little bit.

So now back to the


. I wanted to sort by AssignedTo user, this can be easily changed by changing the


field of the


I also chose for this example to display the information in a useful grid. This too can be changed as needed.

$allincidents | Sort-Object -Property Assignedto | Select-Object -Property ID, Displayname, AffectedUser, Assignedto | Out-GridView

You will get some results like the below.


You can also limit the results by “Assigned To” user like such using either




operators. Examples below

-like operator. The example is finding all calls assigned to a user where the name is like “Kok*”. This time without the “out-gridview”

$allincidents | Where-Object {$_.assignedto.displayname -like "kok*"} 


-eq operator. This example finds all incidents assigned to a user with a specific name. In my example I am using “Desmond Hilton”

$allincidents | Where-Object {$_.assignedto.displayname -eq "Desmond Hilton"}


The PowerShell code can be easily adapted to meet the requirements for the “Affected User”. We simply change the value to use with the current object like such. I use


on “Affecteduser”


. Again you can use the





$allincidents | Where-Object {$_.assignedto.displayname -like "kok*"} 

-like operator. In this example I am using the Name “like” Roland

$allincidents | Where-Object {$_.affecteduser.DisplayName -like "Roland*"}


-eq operator. In this example I am using the “Affected User” name of “Andre Botes”

$allincidents | Where-Object {$_.affecteduser.DisplayName -eq "andre Botes"}


This should help you to make more in-depth queries and enjoy using PowerShell and SMLets to get valuable information from System Center Service Manager.

I have also setup an new e-mail address to help with Service Manger queries. you can e-mail me at systemcenterguyza ”at” live ”dot” com  ( and I will assist as much as I can.

I have also setup a new Twitter account to focus the Information around the System Center Suite.



Follow me.