All:

I am working on a function for enabling users in Lync based off AD Group 
memberships. I am interested in the best practice when attempting to have 
try/catch perform an action only if there are no errors. I'll include the 
entire code at the end of the email, but what I am curious about is this 
specific piece:

If($Email -ne $Null)
{
    try
    {
        Enable-CsUser $Member.Name -RegistrarPool $RegistrarPool -SipAddress 
"sip:$($Email)" -ErrorAction Stop
Enable-UserSuccess
    }
    catch
    {
        Enable-UserFailed
    }
}
Else
{
    Enable-UserFailed -Issue Email
}


Should the Enable-UserSuccess be called outside of the try block like this?


If($Email -ne $Null)
{
    try
    {
        Enable-CsUser $Member.Name -RegistrarPool $RegistrarPool -SipAddress 
"sip:$($Email)" -ErrorAction Stop
    }
    catch
    {
        Enable-UserFailed
    }
    If(!$Error)
    {
        Enable-UserSuccess
    }
}
Else
{
    Enable-UserFailed -Issue Email
}


My logic for changing to using the If(!$Error) statement is in the first 
example if my event logging fails, then the entire try block fails, so the user 
would not get enabled in Lync. If the user account can be created, I want it 
created. The logging is there for myself/others, but is not critical to the 
success of the function. Anyway, here is the full code, in case it's necessary. 
I apologize in advance for any formatting blunders. I've been reviewing the PS 
Styling documentation on GitHub (for those 
interested<https://github.com/PoshCode/PowerShellPracticeAndStyle/tree/master/Style%20Guide>)
 and am trying to adhere to it, but still not 100% cleaned up pre-existing 
scripts:


Function Enable-LyncUsers
{
    Param(
        # Group to parse members and enable in Lync
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        $CSGroup,

        # Registrar Pool to assign new Lync users
        [Parameter(Mandatory=$false,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]
        $RegistrarPool = "AHPFILER.aspirehealthplan.org"
    )

    function Write-Log {
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory=$true,
                   Position=0)]
        [string]
        $Message
    )

    $LogDirectory = "\\ahpmgmt\logs$\Lync\Enable_Users"
    $LogFile = "$(Get-Date -UFormat "%Y.%m.%d") - Enable Lync Users.log"

    If(-not (Test-Path "$LogDirectory\$($LogFile)"))
    {
        New-Item -Path $LogDirectory -Name $LogFile -ItemType File
    }

    Add-Content -Path "$($LogDirectory)\$($LogFile)" -Value "$(Get-Date) | 
$Message$newLine"

}

    function Enable-UserFailed {
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory=$false,
                   Position=0)]
        [string]
        $Source = "Enable Lync User",
        [Parameter(Mandatory=$false,
                   Position=0)]
        [string]
        $Issue
    )

        If(-Not [System.Diagnostics.EventLog]::SourceExists($Source))
        {
            [System.Diagnostics.EventLog]::CreateEventSource($Source,'Lync 
Server')
        }

        If($Issue -eq "Email")
        {
            $Event = @{
            LogName = "Lync Server"
            Source = $Source
            EventID = 8414
            EntryType = "Warning"
            Message = "Failed to enable user, email not found: 
$($User.GivenName) $($User.Surname)"
        }
            Write-EventLog @Event
        }
        Else
        {
            $Event = @{
            LogName = "Lync Server"
            Source = $Source
            EventID = 8414
            EntryType = "Error"
            Message = "Failed to enable user: $($User.GivenName) 
$($User.Surname)"
        }
            Write-EventLog @Event
        }
}

    function Enable-UserSuccess {
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory=$false,
                   Position=0)]
        [string]
        $Source = "Enable Lync User"
    )

        If(-Not [System.Diagnostics.EventLog]::SourceExists($Source))
        {
            [System.Diagnostics.EventLog]::CreateEventSource($Source,'Lync 
Server')
        }

        $Event = @{
                LogName = "Lync Server"
                Source = $Source
                EventID = 8414
                EntryType = "Information"
                Message = "User Enabled: $($User.GivenName) $($User.Surname)"
            }
            Write-EventLog @Event
}

    Import-Module ActiveDirectory
    Import-Module Lync
    $Members = Get-ADGroupMember $CSGroup -Recursive

    Foreach($Member in $Members)
    {
        $Account = Get-CsUser -Identity $Member.SamAccountName -ErrorAction 
SilentlyContinue
        If($Account.Enabled -ne $True)
        {
            $User = Get-ADUser $Member.SamAccountName -Properties Mail
            $Email = $User.Mail
            If($Email -ne $Null)
            {
                try
                {
                    Enable-CsUser $Member.Name -RegistrarPool $RegistrarPool 
-SipAddress "sip:$($Email)" -ErrorAction Stop
                    Enable-UserSuccess
                    Write-Log "Lync User Enabled: $($User.GivenName) 
$($User.Surname)"
                }
                catch
                {
                    Enable-UserFailed
                    Write-Log "Failed to enable user: $($User.GivenName) 
$($User.Surname)"
                }
            }
            Else
            {
                Enable-UserFailed -Issue Email
                Write-Log "No email found for user: '$($User.GivenName) 
$($User.Surname)'"
            }
        }
    }
}

Confidentiality Notice: This is a transmission from Community Hospital of the 
Monterey Peninsula. This message and any attached documents may be confidential 
and contain information protected by state and federal medical privacy 
statutes. They are intended only for the use of the addressee. If you are not 
the intended recipient, any disclosure, copying, or distribution of this 
information is strictly prohibited. If you received this transmission in error, 
please accept our apologies and notify the sender. Thank you.



Reply via email to