functions embedded in a powershell script

advertisements

So I have the following code which has a foreach loop to pull some group membership data. At the end of the code, I want to recalculate the data and write it again for confirmation. I was wondering what the best way of keeping this clean and concise would be? I know in java for example, I would just create a method and call it each time but am not sure if that holds true in powershell.

I apologize if I am misusing terminology - I am trying to pick this up as I go along

$User = read-host -Prompt "User Name"
$user_dn = (get-mailbox $user).distinguishedname

"Finding all groups that $user is a member of..."

$membership = foreach ($group in get-distributiongroup -resultsize unlimited){
    if ((get-distributiongroupmember $group.identity | select -expand distinguishedname) -contains $user_dn)
        {$group.alias}
}
" "
"----------------------"
$membership
"----------------------"
" "

"Would you like to remove $user from all distribution groups? Press 1 for yes, or 2 for no."
$opt = read-host "1 - yes, 2 - no"
write-host $opt
switch ($opt){
1{
foreach ($a in $membership){
    Remove-DistributionGroupMember -Identity $a -Member $user
    }
}
2{
"No action taken.  Goodbye"
}
}


Yes, you can define functions in PowerShell. Check out Get-Help About_Functions for a tutorial on how to write them. Also, remember that the function must be defined before it is called in the script. I usually just define all my functions at the top of the script.