Archive for: ‘November 2014’

Useful PowerShell snippets – Get-UserByEmail

November 10, 2014 Posted by Anders Asp

Here’s another useful PowerShell snippet which I created when I built my PowerShell Exchange Connector for SCSM. The function itself will return the user object of the given e-mail address. If no user is found you also have to option to create the user object using the -CreateUser switch.

The function have the following parameters:

-EmailAddress
The e-mail address of the user who you want to retrieve

-CreateUser
If this switch is enetered, the function will create a user object if no match is found in the CMDB

-Name
If you know the name of the user that you might create, you can specify the name of the object in this parameter

The script itself:


# This function will return the user object of the specified Email Address. If a matching user isn't found, the function can create an Internal user within the SCSM CMDB
# NOTE: SMlets must be loaded in order for the function to work

Function Get-UserByEmail {
    param (
        [parameter(Mandatory=$True,Position=0)]$EmailAddress,
        [parameter(Mandatory=$False,Position=1)][switch]$CreateUser,
        [parameter(Mandatory=$False,Position=2)]$Name

    )

    # Get all the classes and relationships
    $UserPreferenceClass = Get-SCSMClass System.UserPreference$
    $UserPrefRel = Get-SCSMRelationshipClass System.UserHasPreference$
    $ADUser = Get-SCSMClass Microsoft.Ad.User$
 
    # Check if the user exist
    $SMTPObj = Get-SCSMObject -Class $UserPreferenceClass -Filter "DisplayName -like '*SMTP'" | ?{$_.TargetAddress -eq $EmailAddress}

    If ($SMTPObj) {
        # A matching user exist, return the object

        # If, for some reason, several users are found, return the first one
        If ($SMTPObj.Count -gt 1) {$SMTPObj = $SMTPObj[0]}

        $RelObj = Get-SCSMRelationshipObject -TargetRelationship $UserPrefRel -TargetObject $SMTPObj
        Return $AffectedUser = Get-scsmobject -Id ($RelObj.SourceObject).Get_Id()

    } elseif ($CreateUser -and !$SMTPObj) {
        # A matching user does NOT exist. Do some processing to get the needed properties for creating the user object
        If (!$Name -or $Name -eq '') {
            $Name = $EmailAddress.Substring(0,$EmailAddress.IndexOf("@"))
            $UserName = $Name.Replace(",","")
            $UserName = $UserName.Replace(" ","")
        } else {
            $Name = $Name
            $UserName = $Name.Replace(",","")
            $UserName = $UserName.Replace(" ","")
        }

        # Try Username to make sure we have a unique username
        $Loop = $TRUE
        $i = 1

        While ($Loop -eq $TRUE) {
            $tempUser = Get-SCSMObject -Class (Get-SCSMClass System.Domain.User$) -Filter "UserName -eq $UserName"

            If ($tempUser) {
                $UserName = $UserName + $i
                $i = $i +1
            } elseif ($i -gt 15) {
                Throw "Unable to find a unique username for the new user"
            } else {
                $Loop = $False
            }
        }

        # Create the Property Hash for the new user object
        $PropertyHash = @{"DisplayName" = $Name;
                            "Domain" = "SMINTERNAL";
                            "UserName" = $UserName;
        }

        # Create the actual user object
        $AffectedUser = New-SCSMObject -Class (Get-SCSMClass System.Domain.User$) -PropertyHashtable $PropertyHash -PassThru

        # Add the SMTP notification address to the created user object

        If ($AffectedUser) {
            $NewGUID = ([guid]::NewGuid()).ToString()

            $DisplayName = $EmailAddress + "_SMTP"

            $Projection = @{__CLASS = "System.Domain.User";
                            __SEED = $AffectedUser;
                            Notification = @{__CLASS = "System.Notification.Endpoint";
                                             __OBJECT = @{Id = $NewGUID;
                                                          DisplayName = $DisplayName;
                                                          ChannelName = "SMTP";
                                                          TargetAddress = $EmailAddress;
                                                          Description = $EmailAddress;
                                             }
                            }
            }

            New-SCSMObjectProjection -Type "System.User.Preferences.Projection" -Projection $Projection

        }

        # Return the created user object
        Return $AffectedUser


    }

}

Using the function to retrieve a user:

ScriptSyntax

 

Using the -CreateUser switch:

ScriptSyntax2

User

Notification

You can also download the whole script as a file here: Get-UserByEmail

Useful PowerShell snippets – Add-SRComment

November 1, 2014 Posted by Anders Asp

I will be posting a series of PowerShell snippets that you can use together with Service Manager. This first one is a function called “Add-SRComment” it is simply used whenever you would like to add an End User or Analyst comment to one of your Service Requests. I’ve been using this a lot when doing automated stuff in SCO and SMA lately.

The function have the following parameters:

-SRObject
Requires the actual SR object to which you would like to add the comment.

-Comment
Requires the comment to add to the action log

-EnteredBy
Requires the name of the person who’s writing the comment

-AnalystComment
Switch to Analyst comment instead of End User comment

-IsPrivate
Switch to a Private comment instead of a public comment

The script itself:


# This function adds a comment to the SR Action Log
# NOTE: SMlets must be loaded in order for the function to work

Function Add-SRComment {
    param (
        [parameter(Mandatory=$True,Position=0)]$SRObject,
        [parameter(Mandatory=$True,Position=1)]$Comment,
        [parameter(Mandatory=$True,Position=2)]$EnteredBy,
        [parameter(Mandatory=$False,Position=3)][switch]$AnalystComment,
        [parameter(Mandatory=$False,Position=4)][switch]$IsPrivate
    )

    # Make sure that the SR Object it passed to the function
    If ($SRObject.Id -ne $NULL) {
        

        If ($AnalystComment) {
            $CommentClass = "System.WorkItem.TroubleTicket.AnalystCommentLog"
            $CommentClassName = "AnalystCommentLog"
        } else {
            $CommentClass = "System.WorkItem.TroubleTicket.UserCommentLog"
            $CommentClassName = "EndUserCommentLog"
        }

        # Generate a new GUID for the comment
        $NewGUID = ([guid]::NewGuid()).ToString()

        # Create the object projection with properties
        $Projection = @{__CLASS = "System.WorkItem.ServiceRequest";
                        __SEED = $SRObject;
                        EndUserCommentLog = @{__CLASS = $CommentClass;
                                            __OBJECT = @{Id = $NewGUID;
                                                        DisplayName = $NewGUID;
                                                        Comment = $Comment;
                                                        EnteredBy = $EnteredBy;
                                                        EnteredDate = (Get-Date).ToUniversalTime();
                                                        IsPrivate = $IsPrivate.ToBool();
                                            }
                        }
        }

        # Create the actual comment
        New-SCSMObjectProjection -Type "System.WorkItem.ServiceRequestProjection" -Projection $Projection
    } else {
        Throw "Invalid Service Request Object!"
    }
}

Script syntax

Comment
You can also download the whole script as a file here: Add-SRComment