Repository navigation
Expand file tree
/
Copy pathGeneralFunctions.psm1
More file actions
executable file
·766 lines (642 loc) · 27.8 KB
/
Copy pathGeneralFunctions.psm1
File metadata and controls
executable file
·766 lines (642 loc) · 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
<#
.Synopsis
This script creates functions for general use by other scripts and users
#>
function SetGeneralRoot {
<#
.synopsis
this function sets a script variable for the root folder of General functions.
#>
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
if (Test-Path "$global:GeneralRoot\GeneralFunctions.psm1") {
return
} elseif (Test-Path "$($MyInvocation.PSScriptRoot)\GeneralFunctions.psm1") {
$global:GeneralRoot = $MyInvocation.PSScriptRoot
} elseif (Test-Path "$($MyInvocation.InvocationName)\GeneralFunctions.psm1") {
$global:GeneralRoot = $MyInvocation.InvocationName
} elseif (Test-Path "$($MyInvocation.PSScriptRoot)\General\GeneralFunctions.psm1") {
$global:GeneralRoot = "$($MyInvocation.PSScriptRoot)\General"
} elseif (Test-Path "$($MyInvocation.InvocationName)\General\GeneralFunctions.psm1") {
$global:GeneralRoot = "$($MyInvocation.InvocationName)\General"
} elseif (Test-Path "$(Get-Location | select -ExpandProperty Path)\GeneralFunctions.psm1") {
$global:GeneralRoot = Get-Location | select -ExpandProperty Path
} elseif (Test-Path "$(Get-Location | select -ExpandProperty Path)\GeneralFunctions.psm1") {
$global:GeneralRoot = Split-Path (Get-Location | select -ExpandProperty Path)
} else {
$f = New-Object System.Windows.Forms.FolderBrowserDialog;
(New-Object -ComObject Wscript.Shell).Popup("The script needs to determine the root directory in order to proceed. Please choose the directory which contains the GeneralFunctions.psm1 script in the next window.") | Out-Null
$f.ShowDialog() | Out-Null
$global:GeneralRoot = $f.SelectedPath
}
}
function GetFile {
<# Opens a dialog box to allow a user to select a file;
Returns: a System.Windows.Forms.OpenFileDialog object
with a reference to the file;
#>
[CmdletBinding()]
Param(
[Parameter(HelpMessage='Any warnings you might want to issue to the user. This is optional.')]
[String]$Prompt,
[Parameter(HelpMessage='Optional extensions which you want to see.')]
[ValidateSet("All Files (*.*) | *.*", "CSV | *.csv")]
[String]$Extensions='All Files (*.*)| *.*'
)
if (-not ($Prompt -eq $null -or ($Prompt -eq ''))) {(New-Object -ComObject Wscript.Shell).Popup($Prompt) | Out-Null}
$f = New-Object System.Windows.Forms.OpenFileDialog;
$f.Filter = $Extensions
$f.ShowDialog() | Out-Null
$f
}
function LoadModuleIntoSession {
<#
.synopsis
This function takes an open session (with the machine which has the ActiveDirectory module)
and loads the ActiveDirectory and GeneralFunctions modules into it. It returns the session
with the modules now loaded.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,HelpMessage="An open session with the server running the Active Directory")]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Runspaces.PSSession]$ADSession
)
Invoke-Command -Session $ADSession -ScriptBlock {Import-Module -Name ActiveDirectory}
$ScriptContents = Get-Content -Path "$Global:GeneralRoot\GeneralFunctions.psm1"
$ModuleName = 'GeneralFunctions'
$FileName = "$ModuleName.psm1"
Invoke-Command -Session $ADSession -ScriptBlock {
Param($ScriptContents,$FileName)
Set-Content -Path $FileName -Value $ScriptContents -Force
Import-Module -Name ".\$FileName"
} -ArgumentList ($ScriptContents,$FileName)
$ADSession
}
function NewADUserFromExisting {
<#
.Synopsis
This function creates a new AD User by copying the settings from an existing user's profile
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage="The SAM Account Name for this user")]
[ValidateNotNullOrEmpty()]
[String]$PreWin2kLogon,
[Parameter(Mandatory,HelpMessage="The user's first name")]
[String]$FirstName,
[Parameter(Mandatory,HelpMessage="The user's last name")]
[String]$LastName,
[Parameter(HelpMessage="The user's email address.")]
[String]$Email,
[Parameter(HelpMessage="The fully qualified domain name for the email address")]
[String]$Domain,
[Parameter(Mandatory,HelpMessage="The user's password as a SecureString")]
[System.Security.SecureString]$Password,
[Parameter(Mandatory,HelpMessage="The existing user instance on which you will base this user")]
[ValidateNotNullOrEmpty()]
[String]$OldUser,
[Parameter(HelpMessage="The user's role")]
[String]$RoleTitle,
[Parameter(HelpMessage="The organization name")]
[String]$Organization,
[Parameter(HelpMessage="The user's department")]
[String]$Department
)
if ($Email -eq $null -or ($Email -eq '')) {
$Email = MakeEmailAddress -FirstName $FirstName -LastName $LastName -Domain $Domain
} else {
$Email = ValidateEmailAddress -Email $Email
}
$OUInstance = Get-ADUser -Identity $OldUser -Properties MemberOf,CannotChangePassword,PasswordNeverExpires
New-ADUser -SamAccountName $PreWin2kLogon `
-GivenName $FirstName `
-Surname $LastName `
-Name "$FirstName $LastName" `
-DisplayName "$FirstName $LastName" `
-Title $RoleTitle `
-Department $Department `
-Company $Organization `
-EmailAddress $Email `
-AccountPassword $Password `
-UserPrincipalName $Email `
-Instance $OUInstance `
-Path ((GetParentOrganizationalUnit -ExistingUser $OUInstance).distinguishedName.ToString())
## set the proxyAddress parameter
Set-ADUser -Identity $PreWin2kLogon -Add @{proxyAddresses="SMTP:$Email"} `
-CannotChangePassword $OUInstance.CannotChangePassword `
-PasswordNeverExpires $OUInstance.PasswordNeverExpires
## Add user to old user's membership groups
Select-Object -InputObject $OUInstance -ExpandProperty memberof | ForEach-Object {
$Group = $_.split(',').substring(3)[0]
if (-not (Get-ADGroupMember -Identity $Group | Select-Object -ExpandProperty SamAccountName).Contains($PreWin2kLogon)) {
Add-ADGroupMember -Identity $Group -Members $PreWin2kLogon -ErrorAction Continue
}
} -ErrorAction Continue
}
function NewADUserFromExistingWithHashTable {
<#
.Synopsis
This function takes in a HashTable loaded with new users' details and creates them in the active directory
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage='A HashTable loaded with the details of the new users')]
[PSCustomObject]$HashTable,
[Parameter(Mandatory,HelpMessage='The name of your organization')]
[String]$Organization
)
$HashTable | ForEach-Object {
NewADUserFromExisting -PreWin2kLogon $_.ADLogonID `
-FirstName $_.FirstName `
-LastName $_.LastName `
-Email $_.Email `
-Password (ConvertTo-SecureString -AsPlainText $_.ADPassword -Force) `
-OldUser $_.CloneFromUser `
-RoleTitle $_.Role `
-Organization $Organization `
-Department $_.Department `
}
}
function NewADUserFromExistingWithCsv {
<#
.Synopsis
This function takes the new user parameters from a file and calls the
NewADUserFromExisting-WithHashTable function on it
#>
[CmdletBinding()]
Param(
[Parameter(HelpMessage='The path to the csv file with the user''s details')]
[String]$File=(GetFile),
[Parameter(Mandatory,HelpMessage='The name of your organization')]
[String]$Organization
)
NewADUserFromExistingWithHashTable -HashTable (Import-Csv -Path $File) -Organization $Organization
}
function GetParentOrganizationalUnit {
<#
.Synopsis
Use this function to get the DirectoryEntry type of the parent folder for an AD User
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory,HelpMessage="The existing user account from which you need to draw the Parent OU")]
[Microsoft.ActiveDirectory.Management.ADUser]$ExistingUser
)
[ADSI](([ADSI]"LDAP://$($ExistingUser.DistinguishedName)").Parent)
}
function ValidateEmailAddress {
<#
.Synopsis
Validate input in the format <mailboxName>@<domain>.
.Description
If only an email is provided, the system will check if it is in the format <mailboxName>@<domain>, where domain will be a string containing at least one dot.
If an email and Domain are provided,
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage="The user's email address in the format <mailboxName>@<domain>")]
[ValidateNotNullOrEmpty()]
[String]$Email
)
$Email = $Email.ToLower() -replace '\s', ''
if ($Email -match "^[a-z0-9\-_.]+@[a-z0-9]+\.[a-z0-9]+") {
$Email
} else {
throw "Email parameter must be in the format <mailboxName>@<string1.string2>[.stringN*] and contain only letters, numbers, '@' and/or the '-','_' and '.' punctuation characters"
}
}
function MakeEmailAddress {
<#
.Synopsis
Make an email address in the format <firstname>[.lastName]@<domain>
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage="The user's first name")]
[ValidateNotNullOrEmpty()]
[String]$FirstName,
[Parameter(HelpMessage="The user's last name")]
[String]$LastName,
[Parameter(Mandatory,HelpMessage="The email domain, in the format <string1.string2[.stringN]*>")]
[ValidateNotNullOrEmpty()]
[String]$Domain
)
$Domain = $Domain.ToLower() -replace '\s',''
if ($Domain -match "^@?[a-z0-9]+\.[.a-z0-9]+[a-z0-9]$") {
if (-not ($FirstName -match "^[a-z0-9\-_.]+$")) {
throw "FirstName must contain only letters, numbers and/or the '-','_' and '.' punctuation characters"
}
$Email = $FirstName.ToLower() -replace '\s',''
if (-not ($LastName -eq $null -or ($LastName -eq ''))) {
if ($LastName -match "^[a-z0-9\-_.]+$") {
$Email += '.'+(($LastName.Tolower()) -Replace '\s','')
} else {
throw "LastName must contain only letters, numbers and/or the '-','_' and '.' punctuation characters"
}
}
if (-not ($Domain[0] -eq '@')) {$Domain = '@'+$Domain}
$Email += $Domain
$Email
} else {
throw 'Parameter Domain must be in the format [@]<string1>.<string2>[.stringN]*'
}
}
function AssignLicences {
<#
.Synopsis
This function tries to decouple licence assignment from user creation, using a pattern
similar to the Factory Method to do so.
.Description
This function checks if the user is already licensed and, if not, takes as parameter
an office 365 user and a string with the licence type required, creates the necessary
licence options, then assigns them to the user. Checking if user is licensed can be
bypassed by providing the relevant argument.
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Email,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[ValidateSet("Full","SharepointOnly","ExchangeForLeavers")]
[String]$LicenceType,
[Parameter(HelpMessage="Set to true if you want to override any possible licence the user may already have")]
[Boolean]$Override=$false
)
# The Prepare*Licences functions below should be replaced by the relevant
# organisation-specific functions to return the Office 365 licences for each,
# and were not included here because their implementations were too specific
$MSOlUser = Get-MsolUser -UserPrincipalName $Email
if (($MSOlUser.IsLicensed) -and $Override) {
$LicensesToOverride = $MSOlUser.Licenses.AccountSkuId
Set-MsolUserLicense -UserPrincipalName $Email -RemoveLicenses $LicensesToOverride
$MSOlUser = Get-MsolUser -UserPrincipalName $Email
}
if (-not $MSOlUser.IsLicensed) {
switch($LicenceType) {
"Full" {$Licences = PrepareFullLicences; break}
"SharepointOnly" {$Licences = PrepareSharepointOnlyLicences; break}
"ExchangeForLeavers" {$Licences = PrepareExchangeLeaversLicences; break}
}
$Licences | ForEach-Object { Set-MsolUserLicense -UserPrincipalName $Email `
-AddLicenses "$($_.AccountSkuId.AccountName):$($_.AccountSkuId.SkuPartNumber)" `
-LicenseOptions $_ -ErrorAction Continue
}
} else {
Write-Host "User $Email is already licensed. No new licences assigned." -BackgroundColor Black -ForegroundColor Yellow
}
}
function GetUserLicences {
<#
.Synopsis
This function strips the user of all licences they currently hold
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]$Email
)
$User = Get-MsolUser -UserPrincipalName $Email
$User.Licenses
}
function GetUserLicenceNames {
<#
.Synopsis
This function strips the user of all licences they currently hold
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Email
)
(GetUserLicences -Email $Email).AccountSkuId
}
function RemoveAllLicences {
<#
.Synopsis
This function strips the user of all licences they currently hold
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$Email
)
GetUserLicenceNames -Email $Email | ForEach-Object {
Set-MsolUserLicense -UserPrincipalName $Email -RemoveLicenses $_
}
}
function TestProvision {
<#
.Synopsis
This function will test whether a script block's return type is not null
once every minute for 30 times, or as many as and for as long as specified
on the NumberOfAttempts and SecndsBetweenAttempts parameter. If the script
returns something other than $null before the end of the count, the function
returns true. Otherwise, it will return false.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.ScriptBlock]$Cmdlet,
[int]$NumberOfAttempts=30,
[int]$SecondsBetweenAttempts=60
)
for ($Count = 1; $Count -le $NumberOfAttempts; $Count++) {
if ((Invoke-Command -ScriptBlock $Cmdlet) -eq $null) {
Write-Host "`nAttempt number $Count " -NoNewline
Write-Host "Failed. Will try again in $SecondsBetweenAttempts seconds." -NoNewline
Start-Sleep -Seconds $SecondsBetweenAttempts
} else {
return $true
}
}
return $false
}
function SendMessage {
<#
.SYNOPSIS
This script takes an html message and sends it to the 'To' address in the field
You need the proper permissions on the mailbox from which you are sending the
messages
#>
[CmdletBinding(DefaultParameterSetName='Path')]
Param(
[Parameter(Mandatory, HelpMessage='Your Admin Office 365 credentials',ParameterSetName='Path')]
[Parameter(Mandatory, ParameterSetName='Msg')]
[Alias('Credentials')]
[System.Management.Automation.PSCredential]$Cred,
[Parameter(Mandatory, ParameterSetName='Path',
HelpMessage='the path and filename to the message you would like to send')]
[String]$Path<#=(GetFile -Prompt "Please choose the file with the message you would like to send").Filename#>,
[Parameter(Mandatory, HelpMessage="A string containing the message which you want to send",
ParameterSetName='Msg')]
[String]$Msg,
[Parameter(Mandatory,
HelpMessage='The address to which you want to send the message',
ParameterSetName='Path')]
[Parameter(Mandatory,
ParameterSetName='Msg')]
[String[]]$To,
[Parameter(Mandatory,
HelpMessage='The email from which you want to send the message',
ParameterSetName='Path')]
[Parameter(Mandatory,
ParameterSetName='Msg')]
[String]$From,
[Parameter(Mandatory, HelpMessage='The subject of the email to send out',
ParameterSetName='Path')]
[Parameter(Mandatory,ParameterSetName='Msg')]
[ValidateNotNullOrEmpty()]
[String]$Subject,
[Parameter(HelpMessage='[Optional] If you want it cc''d to anyone',
ParameterSetName='Path')]
[Parameter(ParameterSetName='Msg')]
[String[]]$CC
)
$Body = ""
if ($PSCmdlet.ParameterSetName -eq 'Path') {
Get-Content -Path $Path | ForEach-Object {$Body += $_}
} else {
$Body = $Msg
}
if ($CC.Count -eq 0 -or ($CC[0] -eq '')) {
Send-MailMessage -To $To -Subject $Subject `
-From "$From" -BodyAsHtml:$true `
-SmtpServer 'smtp.office365.com' -Port 587 -UseSsl:$true `
-Credential $Cred -Body $Body -Encoding UTF8
} else {
Send-MailMessage -To $To -Subject $Subject `
-From "$From" -Cc $CC -BodyAsHtml:$true `
-SmtpServer 'smtp.office365.com' -Port 587 -UseSsl:$true `
-Credential $Cred -Body $Body -Encoding UTF8
}
Write-Host "Message sent to $To." -BackgroundColor Black -ForegroundColor Green
}
function MakeHtmlFromTemplate {
<#
.Synopsis
This function takes in a template with placeholders, replaces the placeholders with
arguments provided, then returns html output.
#>
[CmdletBinding()]
Param(
[Parameter(HelpMessage="The path to the file containing the message template")]
[String]$PathToTemplate=(GetFile -Prompt 'Please find the file containing the message template. Make sure that all the placeholders are in the format "\$_[a-z]+"').Filename,
[Parameter(Mandatory,HelpMessage="A hash table containing the placeholder names and the values by which they should be replaced")]
[System.Collections.Hashtable]$Values
)
$Body = ""
Get-Content -Path $PathToTemplate | ForEach-Object {$Body += $_}
$Values.GetEnumerator() | ForEach-Object {$Body = $Body.Replace($_.key,$_.value)}
$Body
}
function GiveMailboxPermissionsWithSMA {
<#
.Synopsis
This function creates an SMA, adds members to it, then gives both
Send As and Full Access permission to the selected mailbox by
adding the SMA to it's permissions and recipient permissions.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage='The name of the security group (e.g. SMA <Mailbox>)')]
[String]$SMAName,
[Parameter(Mandatory,HelpMessage="The email domain, in the format <string1.string2[.stringN]*>")]
[ValidateNotNullOrEmpty()]
[String]$Domain,
[Parameter(Mandatory,HelpMessage="The member or members who will be part of the SMA")]
[ValidateNotNullOrEmpty()]
[String[]]$SMAMembers,
[Parameter(Mandatory,HelpMessage="The mailbox to which the users need to gain access")]
[ValidateNotNullOrEmpty()]
[String]$Mailbox,
[Parameter(HelpMessage="If the SMA should have ReadOnly access, set to true. Default false")]
[ValidateNotNullOrEmpty()]
[Boolean]$ReadOnly=$false
)
if (-not ($SMAName.ToLower().Contains("sma"))) {
$SMAName = "SMA $SMAName"
}
$Alias = $SMAName.Replace(" ","")
$SMAEmail = MakeEmailAddress -FirstName $Alias -Domain $Domain
New-DistributionGroup -Name $SMAName -Alias $Alias -PrimarySmtpAddress $SMAEmail -Members $SMAMembers -Type 'Security'
Set-DistributionGroup -Identity $SMAEmail -HiddenFromAddressListsEnabled $true
Add-MailboxPermission -Identity $Mailbox -AccessRights FullAccess -User $SMAName
if (-not $ReadOnly) {
Add-RecipientPermission -Identity $Mailbox -AccessRights SendAs -Trustee $SMAEmail
}
}
function CopySPAccess {
<#
.Synopsis
This function takes in a "source" and "target" users' email addresses and adds
the test user to exactly the same groups as the legitimate one. This allows you to
test what exactly the legitimate user can see on Sharepoint to make sure that
they have the righ access.
#>
[CmdletBinding()]
Param(
[Parameter(HelpMessage='The source user''s O365 email')]
[String]$SourceUser=(Read-Host -Prompt 'Please enter the user''s O365 email address'),
[Parameter(HelpMessage='The TargetUser user''s O365 email')]
[String]$TargetUser=(Read-Host -Prompt 'Please enter the user''s O365 email address'),
[Parameter(Mandatory,HelpMessage="The URL for your Sharepoint team site")]
[ValidateNotNullOrEmpty()]
[String] $SPSite
)
# remove TargetUser user from all groups it is currently in
Get-SPOUser -Site $SPSite -LoginName $TargetUser | select -ExpandProperty groups | % {Remove-SPOUser -Site $SPSite -LoginName $TargetUser -Group $_}
# add test user to the groups of the chosen user
Get-SPOUser -Site $SPSite -LoginName $SourceUser | select -ExpandProperty groups | % {Add-SPOUser -Site $SPSite -LoginName $TargetUser -Group $_}
}
function GetUserDGMembership {
<#
.synopsis
This function returns all the distribution groups of which a user is a member
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage='The user''s Office 365 account')]
[String]$UserEmail
)
$UserMailbox = Get-Mailbox -Identity $UserEmail -ErrorAction SilentlyContinue
$Exists = [bool]$UserMailbox
if ($Exists) {
Write-Host "Retrieving distribution groups of which $UserEmail is a member..." -BackgroundColor Black -ForegroundColor Cyan
$DistributionGroups = Get-DistributionGroup -ResultSize Unlimited | Where-Object {
(Get-DistributionGroupMember -Identity $_.PrimarySmtpAddress -ResultSize Unlimited | Where-Object {
$_.PrimarySmtpAddress -eq $UserEmail
}) -ne $null
}
if ($DistributionGroups -ne $null) {
Write-Host "Member of: $($DistributionGroups -join ", ")" -BackgroundColor Black -ForegroundColor Cyan
$DistributionGroups
} else {
Write-Host "$UserEmail not found in any distribution groups." -BackgroundColor Black -ForegroundColor Green
}
} else {
Write-Host "$UserEmail does not have a mailbox." -BackgroundColor Black -ForegroundColor Green
}
}
function RemoveUserFromDistributionGroups {
<#
.synopsis
This function iterates through all distribution groups and removes the user from them
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage='The user''s Office 365 account')]
[String]$UserEmail
)
$DistributionGroups = GetUserDGMembership -UserEmail $UserEmail
if ($DistributionGroups -ne $null) {
Write-Host "Removing $UserEmail from distribution groups..."
$DistributionGroups | ForEach-Object {
Remove-DistributionGroupMember -Identity $_.PrimarySmtpAddress `
-Member $UserEmail -Confirm:$false
}
Write-Host "done."
}
}
function BlockOffice365Account {
<#
.synopsis
This function will block an office 365 account from signing in
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage='Your Admin Office 365 credentials')]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]$Cred,
[Parameter(Mandatory,HelpMessage='The user''s office 365 account id')]
[String]$Email,
[Parameter(HelpMessage='Set to true if the session is already connected to Azure Active Directory. False by default.')]
[Boolean]$AlreadyConnected=$false
)
if(-not $AlreadyConnected) {
ConnectToMSOnline -Cred $Cred
}
Set-MsolUser -UserPrincipalName $Email -BlockCredential $true -ErrorAction Stop
Write-Host "$Email is now blocked."
}
function GetEmailFromADAccount {
[CmdletBinding()]
Param(
[Parameter(HelpMessage='An optional already open session with Active Directory')]
[System.Management.Automation.Runspaces.PSSession]$ADSession,
[Parameter(HelpMessage='The user''s AD Account loging (e.g. jsmith for John Smith)',ParameterSetName='ADAccount',Mandatory)]
[String]$LocalUserName
)
Invoke-Command -Session $ADSession -ScriptBlock {
Param($LocalUserName)
Get-ADUser -Identity $LocalUserName | Select-Object -ExpandProperty UserPrincipalName
} -ArgumentList $LocalUserName
}
function UserHasExchangeLicence {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]$Email
)
$Exchange = GetUserLicences -Email $Email | Select-Object -ExpandProperty ServiceStatus | Where-Object {
$_.serviceplan.servicename -like '*exchange*' -and ($_.provisioningstatus -ne 'Disabled')
}
if ($Exchange -eq $null) {
$false
} else {
$true
}
}
function SendMessage {
<#
.SYNOPSIS
This script takes an html message and sends it to the 'To' address in the field
You need the proper permissions on the mailbox from which you are sending the
messages
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory,HelpMessage='Your Admin Office 365 credentials')]
[Alias('Credentials')]
[System.Management.Automation.PSCredential]$Cred,
[Parameter(Mandatory,HelpMessage='the path and filename to the message you would like to send')]
[String]$Path,
[Parameter(Mandatory,HelpMessage='The address to which you want to send the message')]
[String]$To,
[Parameter(Mandatory,HelpMessage='The email from which you want to send the message')]
[String]$From,
[Parameter(Mandatory,HelpMessage='The subject of the email to send out')]
[String]$Subject,
[Parameter(HelpMessage='[Optional] If you want it cc''d to anyone')]
[String[]]$CC
)
try {
$Body = ""
Get-Content -Path $Path | ForEach-Object {$Body += $_}
Send-MailMessage -To $To -Subject $Subject `
-From "$From" -Cc $CC -BodyAsHtml:$true `
-SmtpServer 'smtp.office365.com' -Port 587 -UseSsl:$true `
-Credential $Cred -Body $Body
Write-Host "Message sent to $To." -BackgroundColor Black -ForegroundColor Green
} catch [System.Exception] {
throw $_
}
}
function LoadProperties {
<#
.SYNOPSIS
This function loads properties from a file
#>
[CmdletBinding()]
Param(
[Parameter(HelpMessage='Path to the properties file to be loaded')]
[String]$File=(GetFile).FileName
)
ConvertFrom-StringData (Get-Content $File -raw)
}