Functions within a script

Welcome Forums General PowerShell Q&A Functions within a script

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
3 weeks, 4 days ago.

  • Author
    Posts
  • #178122

    Participant
    Topics: 26
    Replies: 41
    Points: 133
    Rank: Participant

    I want to define a function within a script and then consume it in the same script. This function will use 2 variables. These variables are defined as part of a parameter set or defined from csv input for use in other places in the script.

    Will the function be able to consume these variables or will they have to be specifically passed to it via a parameter set?

  • #178137

    Participant
    Topics: 0
    Replies: 45
    Points: 240
    Helping Hand
    Rank: Participant

    Please give some sample what you are try to accomplish....

    You can use $script scope of variable then you don't need to declared any variable inside the function.you can easily use same variable through out the script anywhere.

    Thanks,

    Nitesh

  • #178149

    Participant
    Topics: 2
    Replies: 496
    Points: 1,221
    Helping Hand
    Rank: Community Hero

    The function can utilise variables defined by the script directly. I would advise against it as a general practice, though. As Evila mentions, you can specifically scope such a variable ($script:VarName) in order to explicitly target a variable defined in the script. That's better but it's not foolproof. It isn't a good habit to get into, and I'd advise in almost every possible case that it's better just to pass the values as function parameters. It will make debugging the script much less complicated in future, as you'll always see exactly what input the function is getting. 🙂

  • #178296

    Participant
    Topics: 26
    Replies: 41
    Points: 133
    Rank: Participant

    So let me provide some clarification. This is a module for part of our termination process and uses parameter sets and switching to provide either csv input or individual parameter input.

    I want to define the function and then call it to run the process. The variables used in the script are defined in the parameter set and populated either at run or from the csv file.

    I want to take the section of script from line 75 to line 86 and create a function and then call the function. The variables have already been defined in the initial parameter set which is why I was asking if I had to recreate the parameters as part of the function and pass them that way.

    
    function Create-ForwardGroups
    {
    	
    < #
    .SYNOPSIS
    Moves ad account to DisabledUsers OU. Pauses to allow sync to be disabled.   Creates unified groups for forwarding of email.
    .SYNTAX
     Create-ForwardGroups [-Path] [-MyMail]  
    .DESCRIPTION
    Create-ForwardGroups requires access to AD and O365.   This requires a csv input. Using these connections it moves the user account to the disabledusers OU.  Pauses for 30 minutes to allow time for sync to O365 to take place.   
    After 30 minutes a unified group will be created as a forwarder and an email will be sent to the recipient.  
    .PARAMETER Path
    The path where the input .csv file is located.  A folder named forwarding is expected.
    .PARAMETER MyMail
    The email address of the person executing the script
    .PARAMETER Mail
    The email address of the employee whose mail is being forwarded
    .PARAMETER Sam
    The legacy logon name for the employee whose mail is being forwarded (e.g. jdoe, nc10075)
    .PARAMETER Name
    The friendly name for the employee whose mail is being forwarded.  (e.g. John Doe, Jane Doe), this name will be entered with quotes.  "Jane Doe", "John Doe"
    .PARAMETER Recipient
    The email address for the person who will be receiving the forwarded mail.
    .EXAMPLE
    Create-ForwardGroups -Path c:\temp\forwarding\xxx.csv -MyMail john.doe@contoso.com
    .EXAMPLE
    Create-ForwardGroups -MyMail jane.hancock@contoso.com -Name "John Doe" -Sam jdoe -Mail john.doe@contoso.com -Recipient Jane.Manager@contoso.com
    #>	
    	
    	
    	[CmdletBinding()]
    	param (
    		[Paramater(Mandatory = $true)]
    		[string]$MyMail,
    		
    		[Parameter(Mandatory = $true,
    		ParameterSetName = "CsvInput")]
    		[string]$Path,
    		
    		[Parameter(Mandatory = $True,
    		ParameterSetName = "Individual")]
    		[string]$Mail,
    		[string]$Sam,
    		[string]$Recipient,
    		[string]$Name
    	)
    	
    $EmailBody = @"
    
    
    

    Email forwarding for VarName has been created. We are now using Office 365 groups to handle email forwarding for terminated employees, it will work differently than what has been done before.

    When you no longer need the email forwarded to you, you can delete the group using the instructions below. NOTE: O365 groups are automatically set to expire after 180 days. Beginning at 150 days you will receive several email notifications, spaced across a 30 day period, asking if you want to renew the group. If you do not renew the group, (by clicking the renew button in the automated email message) it will be deleted. It can be recovered if requested within 30 days, but is permanently deleted after that.

    To delete the group:

    1. Expand the Groups section (located in the left navigation pane) in Outlook and select the desired #Forwarder group.
    2. On the ribbon bar choose `'Group Settings -> Edit Group`'.
    3. Select `'Delete Group`' from the bottom left corner of the dialog box.
    4. In the Pop-Up dialog box, check the box `'I understand that all group content will be deleted`'. This ONLY refers to items in the group. Items that were forwarded to your inbox will not be affected.
    "@ switch ($PSCmdlet.ParameterSetName) { "Individual"{ $displayname = "#Forwarder-" + $Name $alias = "#" + $Sam + "forwarder" new-unifiedgroup -DisplayName $displayname -alias $alias -primarysmtpaddress $Mail -accesstype private -autosubscribenewmembers -requiresenderauthentication:$false set-unifiedgroup -Identity $displayname -hiddenfromaddresslistsenabled:$true -UnifiedGroupWelcomeMessageEnabled:$false Add-UnifiedGroupLinks -Identity $displayname -LinkType Members -Links $Recipient Add-UnifiedGroupLinks -Identity $displayname -LinkType Owners -Links $Recipient Remove-UnifiedGroupLinks -Identity $displayname -LinkType Owners -Links $MyMail -confirm:$false Remove-UnifiedGroupLinks -Identity $displayname -LinkType Members -Links $MyMail -confirm:$false $EmailBody = $EmailBody.Replace("VarName", $Name) Send-MailMessage -to $Recipient -Subject "DO NOT REPLY: Email Forwarding for $Name" -From 'TerminationProcess@contoso.com' -Body $emailbody -bodyashtml -SmtpServer smtp.Commscope.com -port 25 $EmailBody = $EmailBody.Replace($Name, "VarName") } "CsvInput"{ $sheets = get-ChildItem "$Path\forwarding\*.csv" $csvpath = "$Path\Forwarding\" $NewDN = "OU=Disabled Users,DC=Contoso,DC=COM" foreach ($item in $sheets) { $filename = $item.name $filename $tasks = Import-csv "$csvpath\$filename" foreach ($i in $tasks) { $filter = $i.cmail $dn = get-aduser -filter 'Mail -like $filter' -properties distinguishedName | select -ExpandProperty distinguishedName Move-ADObject $dn -TargetPath $NewDN } } $x = 30 * 60 $length = $x / 100 while ($x -gt 0) { $min = [int](([string]($x/60)).split('.')[0]) $text = " " + $min + " minutes " + ($x % 60) + " seconds left" Write-Progress "Pausing Script" -status $text -perc ($x/$length) start-sleep -s 1 $x-- } foreach ($item in $sheets) { $filename = $item.name $filename $tasks = Import-Csv "$csvpath\$filename" foreach ($i in $tasks) { $mail = $i.cmail $sam = $i.sam $Name = $i.firstname + " " + $i.lastname $displayname = "#Forwarder-" + $name $alias = "#" + $sam + "forwarder" $Recipient = $i.forwardtoa new-unifiedgroup -DisplayName $displayname -alias $alias -primarysmtpaddress $mail -accesstype private -autosubscribenewmembers -requiresenderauthentication:$false set-unifiedgroup -Identity $displayname -hiddenfromaddresslistsenabled:$true -UnifiedGroupWelcomeMessageEnabled:$false Add-UnifiedGroupLinks -Identity $displayname -LinkType Members -Links $Recipient Add-UnifiedGroupLinks -Identity $displayname -LinkType Owners -Links $Recipient Remove-UnifiedGroupLinks -Identity $displayname -LinkType Owners -Links $MyMail -confirm:$false Remove-UnifiedGroupLinks -Identity $displayname -LinkType Members -Links $MyMail -confirm:$false $displayname $EmailBody = $EmailBody.Replace("VarName", $name) Send-MailMessage -to $members -Subject "DO NOT REPLY: Email Forwarding for $Name" -From 'TerminationProcess@contoso.com' -Body $emailbody -bodyashtml -SmtpServer smtp.Contoso.com -port 25 $EmailBody = $EmailBody.Replace($Name, "VarName") } } } } }

You must be logged in to reply to this topic.