-
Notifications
You must be signed in to change notification settings - Fork 1
/
TeamsAACQTools.psm1
3521 lines (3045 loc) · 186 KB
/
TeamsAACQTools.psm1
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class NasCQ {
# Call Queue Name without the 'Optional' prefix
[string]$Name
[String]$DisplayName
#Custom input resource account name (What the end users will see when searching/calling in Teams)
[string]$ResourceAccName
[string]$ResourceAccountUPN
[string]$CleanedRAName
# Tenant domain in the following format: <YourTenant.onmicrosoft.com> or <domain.com>
[ValidatePattern('^*.*')]
[string]$TenantDomain
# [OPTIONAL] Custom prefix for the call queue name
[string]$Prefix
# Call queue GUID populated once the call queue has been built
[guid]$GUID
# Call queue routing method required
[ValidateSet('Attendant','Serial','RoundRobin','LongestIdle')]
[string]$RoutingMethod = 'Attendant'
# Call queue greeting music
[string]$WelcomeMusicAudioFileId
# Specify $True for default music on hold
[ValidateSet('Y','N',$true,$false)]
[string]$UseDefaultMusicOnHold
# Agents to be added to the call queue
[NasCQAgent[]]$Agents
#Enable/disable presence based routing
[ValidateSet('Y','N',$true,$false)]
[string]$PresenceBasedRouting
# Set $True or $False for agent opt out
[ValidateSet('Y','N',$true,$false)]
[string]$AllowOptOut
# Agent alert time in seconds
[int]$AgentAlertTime
# Call queue overflow call limit
[int]$OverflowThreshold
# Call queue overflow action
[ValidateSet('Disconnect','Forward','Voicemail','SharedVoicemail')]
[string]$OverflowAction = 'Disconnect'
# ObjectID of the overflow target e.g. UserA - GUID 01234-01234-123456-0000. Use the GUID
[string]$OverflowActionTarget
# Greeting to the caller when transfered to shared voicemail on overflow (Audio File ID)
[string]$OverflowSharedVoicemailAudioFilePrompt
# Greeting to the caller when transfered to shared voicemail on overflow (Text-to-Speech)
[string]$OverflowSharedVoicemailTextToSpeechPrompt
# Call queue imeout threshold in seconds
[int]$TimeoutThreshold
#Call queue timeout action required - Default 'Disconnect'
[ValidateSet('Disconnect','Forward','Voicemail','SharedVoicemail')]
[string]$TimeoutAction = 'Disconnect'
# ObjectID of the timeout target e.g. UserA - GUID 01234-01234-123456-0000. Use the GUID
[string]$TimeoutActionTarget
# Greeting to the caller when transfered to shared voicemail on timeout (Audio File ID)
[string]$TimeoutSharedVoicemailAudioFilePrompt
# Greeting to the caller when transferred to shared voicemail on timeout (Text-to-Speech)
[string]$TimeoutSharedVoicemailTextToSpeechPrompt
# Id of the channel to connect a call queue to
[string]$ChannelId
# GUID of one of the owners of the team the channels belongs to
[string]$ChannelUserObjectId
# Enable/disable conference mode
[ValidateSet('Y','N',$true,$false)]
[string]$ConferenceMode
# lets you add all the members of the distribution lists to the Call Queue. Use the DL GUID.
[string[]]$DistributionLists
# Turn on transcription for voicemails left by a caller on overflow
[ValidateSet('Y','N',$true,$false)]
[string]$EnableOverflowSharedVoicemailTranscription = 'N'
# Turn on transcription for voicemails left by a caller on timeout
[ValidateSet('Y','N',$true,$false)]
[string]$EnableTimeoutSharedVoicemailTranscription = 'N'
# Indicates the language that is used to play shared voicemail prompts
[string]$LanguageID
# Music to play when callers are placed on hold. This is the unique identifier of the audio file.
[string]$MusicOnHoldAudioFileId
# Resource account with phone number to the Call Queue for channel only
[string[]]$OboResourceAccountIds
#Build the display name from the custom prefix
[NasCQ]PopulateDisplayNameFromPrefix(){
$this.DisplayName = "{0}{1}" -f $this.Prefix, $this.Name
return $this
}
[NasCQ]CleanDisplayName(){
$this.DisplayName = Remove-StringSpecialCharacter -String $this.Name
return $this
}
# [OPTIONAL] Specify the Music On Hold Audio File
[string]$MusicOnHoldAudioFilePath
# [OPTIONAL] Specify the Welcome Music Audio File
[string]$WelcomeMusicAudioFilePath
# Object ID(s) of the Resource Account associated with this call queue.
[String[]]$ResourceAccount
# List of phone numbers associated with this call queue
[ValidatePattern('^\+.*')]
[string[]]$PhoneNumber
}
class NasAA {
[string]$Name
[string]$ResourceAccountUPN
#[String]$LanguageID
#[string]$TimeZoneId
#[ValidatePattern('^*.*')]
#[string]$TenantDomain
#[string]$Prefix
[guid]$GUID
[string]$DefaultTargetCallQueue
# Object ID(s) of the Resource Account associated
[String[]]$ResourceAccount
# List of phone numbers associated
[ValidatePattern('^\+.*')]
[string[]]$PhoneNumber
[string]$LanguageID
[string]$TimeZone
[string]$DefaultAction
[string]$DefaultActionTextToSpeech
[string]$DefaultActionTargetUri
# [OPTIONAL] Specify the Welcome Music Audio File
[string]$DefaultActionAudioFilePath
# Nom business hours action
[ValidateSet('Disconnect','Forward','Voicemail','SharedVoicemail')]
[string]$NonBusinessHoursAction = 'Disconnect'
[string]$NonBusinessHoursActionTargetUri
[string]$NonBusinessHoursActionTextToSpeechPrompt
# [OPTIONAL] Specify the NonBusinessHours Music Audio File
[string]$NonBusinessHoursActionAudioFilePath
[string]$BusinessHoursID
[PSCustomObject]$BusinessHours
#[PSCustomObject]$DefaultCallFlow
#[PSCustomObject]$CallFlows
#[PSCustomObject]$CallHandlingAssociations
#[switch]$EnableVoiceResponse
#[PSCustomObject]$ExclusionScope
#[string[]]$GreetingsSettingAuthorizedUsers
#[PSCustomObject]$InclusionScope
#[PSCustomObject]$Operator
#[string]$VoiceId
}
class NasCQAgent {
[string]$AgentUPN
#[string]$DisplayName
[guid]$AgentGuid
NasCQAgent(){}
NasCQAgent([String]$AgentUPN,[guid]$AgentGuid){
$this.AgentUPN = $AgentUPN
$this.AgentGuid = $AgentGuid
}
}
class NasObjLookup {
[string]$TargetName
[guid]$ObjGuid
NasObjLookup(){}
NasObjLookup([String]$TargetName,[guid]$ObjGuid){
$this.TargetName = $TargetName
$this.ObjGuid = $objGuid
}
}
function Remove-StringSpecialCharacter {
<#
.SYNOPSIS
This function will remove the special character from a string.
.DESCRIPTION
This function will remove the special character from a string.
I'm using Unicode Regular Expressions with the following categories
\p{L} : any kind of letter from any language.
\p{Nd} : a digit zero through nine in any script except ideographic
http://www.regular-expressions.info/unicode.html
http://unicode.org/reports/tr18/
.PARAMETER String
Specifies the String on which the special character will be removed
.PARAMETER SpecialCharacterToKeep
Specifies the special character to keep in the output
.EXAMPLE
Remove-StringSpecialCharacter -String "^&*@wow*(&(*&@"
wow
.EXAMPLE
Remove-StringSpecialCharacter -String "wow#@!`~)(\|?/}{-_=+*"
wow
.EXAMPLE
Remove-StringSpecialCharacter -String "wow#@!`~)(\|?/}{-_=+*" -SpecialCharacterToKeep "*","_","-"
wow-_*
.NOTES
Francois-Xavier Cat
@lazywinadmin
lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding()]
param
(
[Parameter(ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[Alias('Text')]
[System.String[]]$String,
[Alias("Keep")]
#[ValidateNotNullOrEmpty()]
[String[]]$SpecialCharacterToKeep
)
PROCESS {
try {
IF ($PSBoundParameters["SpecialCharacterToKeep"]) {
$Regex = "[^\p{L}\p{Nd}"
Foreach ($Character in $SpecialCharacterToKeep) {
IF ($Character -eq "-") {
$Regex += "-"
}
else {
$Regex += [Regex]::Escape($Character)
}
#$Regex += "/$character"
}
$Regex += "]+"
} #IF($PSBoundParameters["SpecialCharacterToKeep"])
ELSE { $Regex = "[^\p{L}\p{Nd}]+" }
FOREACH ($Str in $string) {
Write-Verbose -Message "[INFO] Special character check - Original String: $Str"
$Str -replace $regex, ""
}
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
} #PROCESS
}
function Confirm-InstalledModule {
param (
[Parameter (mandatory = $true)][String]$module,
[Parameter (mandatory = $true)][String]$moduleName
)
# Do you have module installed?
Write-Host "`nChecking $moduleName installed..." -NoNewline
if (Get-Module -ListAvailable -Name $module) {
Write-Host " INSTALLED" -ForegroundColor Green
}
else {
Write-Host " NOT INSTALLED" -ForegroundColor Red
Write-Error "Run again as Administrator and use the ""-InstallModules"" parameter to install the required modules"
break
}
}
function Confirm-NasValidTarget{
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[string]
$Target
)
try{
[guid]::Parse($Target.substring(4).split("@")[0])
[bool]$False
}catch{
[bool]$True
}
}
function Convert-NasImportMusicFile{
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[string]$rootfolder,
[string]$ScriptLocation = (Get-Location).Path,
[string]$ffmpegLocation
)
#Grab the workflows that don't default music on hold set to Y
#Small quirk, some workflows may have 2 queues associated, and therefore two music on hold values, only grab the ones less than 1
$NewMusicFolders = $ImportWorkflows.where({$_.UseDefaultMusicOnHold -ne "Y" -and $($_.UseDefaultMusicOnHold).count -le 1 -or $_.NonBusinessHoursActionAudioFilePath -like "*audio*" -or $_.DefaultActionAudioFilePath -like "*audio*" })
#$NewMusicFolders = $ImportWorkflows
# Lets loop through the NewMusicFolders, create the queue folders, convert the files and move them into the correct folder
ForEach($musicid in $NewMusicFolders){
#Clear the last objects
$OriginalFile,$OriginalFileString,$OriginalPath,$newFile,$newFolderPath = $null
# Check if the queue id music folder exists, if not, create it
if(!(Test-Path -Path $rootfolder\audio\$($musicid.identity))){
Write-Verbose "Creating audio folder: $rootfolder\audio\$($musicid.identity)"
$newFolderPath = "$rootfolder\audio\$($musicid.identity)"
New-Item -Path $newFolderPath -ItemType Directory
}else{
Write-Verbose "Folder $rootfolder\audio\$($musicid.identity) already exists"
}
# Check if it exists, if it exists then start to build out the new converted files
if(Test-Path -Path $rootfolder\audio\$($musicid.identity)){
Write-Verbose "Audio folder already exists, check the location: $rootfolder\audio\$($musicid.identity)"
Write-Verbose "Root folder: $rootfolder"
$OriginalPath = "$rootfolder\RGS\Instances\$($musicid.identity)"
Write-Verbose "Original Path: $OriginalPath"
## Need to figure out a way to loop through a workflow if it has multiple audio files
## Example. Workflow 1 has custom music on hold on the queue, default action audio file, and non business hours action audio file.
if($($musicid.CustomMusicOnHoldFileID)){
Write-Verbose "Custom Music On Hold File ID: $($musicid.CustomMusicOnHoldFileID)"
$OriginalFile = Get-ChildItem -Path $OriginalPath -Recurse -Filter "$($musicid.CustomMusicOnHoldFileID).wav"
}elseif($($musicid.DefaultActionAudioFileID)) {
Write-Verbose "Default Action Audio File ID: $($musicid.DefaultActionAudioFileID)"
$OriginalFile = Get-ChildItem -Path $OriginalPath -Recurse -Filter "$($musicid.DefaultActionAudioFileID).wav"
}elseif($($musicid.NonBusinessHoursActionAudioFileID)){
Write-Verbose "Non Business Hours Action Audio File ID: $($musicid.NonBusinessHoursActionAudioFileID)"
$OriginalFile = Get-ChildItem -Path $OriginalPath -Recurse -Filter "$($musicid.NonBusinessHoursActionAudioFileID).wav"
}else{
Write-Verbose "BALLS! :( No audio File ID found"
}
Write-Verbose "Music on hold file: $($musicid.CustomMusicOnHoldFileID).wav"
Write-Verbose "Default action audio file: $($musicid.DefaultActionAudioFileID).wav"
Write-Verbose "Non business hours action audio file: $($musicid.NonBusinessHoursActionAudioFileID).wav"
#$OriginalFile = Get-ChildItem -Path $OriginalPath -Recurse -Filter "$($musicid.CustomMusicOnHoldFileID).wav"
#$OriginalFile = (Get-ChildItem -Path $OriginalPath -Recurse).where({$_.Name -eq "$($musicid.CustomMusicOnHoldFileID).wav" -or $_.Name -eq "$($musicid.DefaultActionAudioFileID).wav" -or $_.Name -eq "$($musicid.NonBusinessHoursActionAudioFileID).wav"})
Write-Verbose "Original File: $OriginalFile"
# This will be the new file name
$newFile = "$($OriginalFile.basename).mp3"
Write-Verbose "Filename $newfile"
#Change file to string
$OriginalFileString = $OriginalFile.tostring()
# Build the new file path
Write-Verbose "Checking new file path: $OriginalFileString"
$audioFileTestPath = Test-Path -Path "$ScriptLocation\$newFile"
if(!($audioFileTestPath)){
# Execute ffmpeg to convert the file
& $ffmpegLocation -i $OriginalFileString $newFile > $null
Write-Verbose "Original file name: $OriginalFileString"
Write-Verbose "New file name: $newfile"
}else{
Write-Verbose "Audio file already exists in location: ""$ScriptLocation\$newFile"""
}
# Specify the destination of the converted file
$dest = "$rootfolder\audio\$($musicid.identity)"
$pathofconvertedmusic = "$ScriptLocation\$newFile"
# Move the converted file to the destination $dest
$destTestPath = Test-Path -Path "$dest\$newfile"
if(!($destTestPath)){
Move-Item -Path $pathofconvertedmusic -Destination $dest
Write-Verbose "Moved ""$pathofconvertedmusic"" to ""$dest"""
}else{
Write-Verbose """$dest\$newfile"" already exists at the destination path"
}
Write-Verbose "File $OriginalFileString converted to mp3 - result: $newfile"
}else{
Write-Verbose "Folder: $rootfolder\$($musicid.identity) doesn't exist"
}
}
}
function Get-NASTeamsLanguages {
param (
[Parameter(ValueFromPipeline)]
[String]$rootFolder
)
$TeamsLanguages = [PSCustomObject]@{
LanguageID = "ar-EG","ca-ES","da-DK","de-DE","en-AU","en-CA","en-GB","en-IN","en-US",
"es-ES","es-MX","fi-FI","fr-CA","fr-FR","it-IT","ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
"pt-PT","pt-BR","ru-RU","sv-SE","zh-CN","zh-HK","zh-TW","tr-TR","cs-CZ","th-TH","el-GR",
"hu-HU","sk-SK","hr-HR","sl-SI","id-ID","ro-RO","vi-VN"
Name = "Arabic (Egypt)","Catalan (Catalan)","Danish (Denmark)","German (Germany)","English (Australia)",
"English (Canada)","English (United Kingdom)","English (India)","English (United States)","Spanish (Spain)",
"Spanish (Mexico)","Finnish (Finland)","French (Canada)","French (France)","Italian (Italy)","Japanese (Japan)",
"Korean (Korea)","Norwegian, Bokmål (Norway)","Dutch (Netherlands)","Polish (Poland)","Portuguese (Portugal)",
"Portuguese (Brazil)","Russian (Russia)","Swedish (Sweden)","Chinese (Simplified, PRC)","Chinese (Traditional, Hong Kong S.A.R.)",
"Chinese (Traditional, Taiwan)","Turkish (Turkey)","Turkish (Turkey)","Thai (Thai)","Greek (Greek)","Hungarian (Hungary)",
"Slovak (Slovakia)","Croatian (Croatia)","Slovenian (Slovenia)","Indonesian (Indonesia)","Romanian (Romania)","Vietnamese (Vietnam)"
}
$TeamsLanguages | Sort-Object LanguageID | Export-Excel -Path "$rootFolder\AACQDataImport.xlsx" -WorksheetName "Languages" -NoNumberConversion "Name" -BoldTopRow -AutoSize
}
function Get-NASAgentGuid {
[CmdletBinding()]
param (
# Parameter help description
[Parameter(Mandatory=$True,ValueFromPipeline)]
[string[]]$AgentUPN
)
Begin {
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Looking for agents to build the agent objects."
$foundInvalid = $false
}
process {
ForEach-Object {
try{
$TypeObj = (Get-CsOnlineUser -Identity $_ | Get-Member)[0].typename
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Object typename = $TypeObj"
#Try and get the user
if($TypeObj -like "*UserMas"){
$CQAgentGUID = (Get-CsOnlineUser -Identity $_).Identity
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Converted object using new Teams properties: $CQAgentGUID"
}else{
$CQAgentGUID = (Get-CsOnlineUser -Identity $_).id.split(",")[0].split("=")[1]
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Converted object using legacy properties: $CQAgentGUID"
}
} Catch {
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Unable to find object: $($AgentUPN)"
$foundInvalid = $true
}
if($CQAgentGUID){
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Building the object: $($AgentUPN) - ObjectID: $($CQAgentGUID)"
#Create the NasCQAgent object with the agents UPN and objectID
[NasCQAgent]::new($AgentUPN,$CQAgentGUID)
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Object built: $($AgentUPN) - ObjectID: $($CQAgentGUID)"
}else{
Write-Error "$InfoStringPrefix $AgentCheckVerboseTypeString Object doesn't exist: $($AgentUPN)"
}
}
}
End{
if(!($foundInvalid)){
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Object ID(s) found and passed back to the calling function."
}else{
Write-Verbose "$InfoStringPrefix $AgentCheckVerboseTypeString Object ID(s) check complete, found invalid. See error for details."
}
}
}
function Get-NASObjectGuid {
<#
.SYNOPSIS
Synopsis
.DESCRIPTION
Description here.
.EXAMPLE
PS C:\>
This example
.EXAMPLE
Example 2 here
.INPUTS
None.
.OUTPUTS
None.
.NOTES
#>
[CmdletBinding()]
param (
# Parameter help description
[Parameter(Mandatory=$True,ValueFromPipeline)]
[string]$TargetName
)
Begin {
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Finding object ID: $TargetName"
$foundInvalid = $false
}
process {
try{
$TypeObj = (Get-CsOnlineUser -Identity $TargetName -ErrorAction SilentlyContinue | Get-Member -ErrorAction SilentlyContinue)[0].typename
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Object typename = $TypeObj"
#Try and get the user
if($TypeObj -like "*UserMas"){
$objGuid = (Get-CsOnlineUser -Identity $TargetName -ErrorAction SilentlyContinue).Identity
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Converted object using new Teams properties: $objGuid"
}else{
$objGuid = (Get-CsOnlineUser -Identity $TargetName -ErrorAction SilentlyContinue).id.split(",")[0].split("=")[1]
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Converted object using legacy properties: $objGuid"
}
} Catch {
$foundInvalid = $true
}
if($objGuid){
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Building the object: $($TargetName) - ObjectID: $($objGuid)"
#Create the NasCQAgent object with the agents UPN and objectID
[NasObjLookup]::new($TargetName,$objGuid)
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Object built: $($TargetName) - ObjectID: $($objGuid)"
}else{
Write-Error "$ErrorStringPrefix $ObjectCheckVerboseTypeString Object doesn't exist: $($TargetName)"
}
}
End{
if(!($foundInvalid)){
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Object ID found and passed back to the calling function."
}else{
Write-Verbose "$InfoStringPrefix $ObjectCheckVerboseTypeString Object ID check complete, found invalid. See error for details."
}
}
}
function Export-ResponseGroupCallRecords {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[Int32]$Months = 3,
[Parameter(ValueFromPipeline)]
[string]$CallDirection = "Inbound"
)
try {
Write-Verbose "Grabbing services to find the CDR database."
$services = Get-CsService
$sqlSrvFqdn = (($services.where({$_.role -contains "Registrar"})).monitoringdatabase | Select-Object -First 1).split(":")[1]
Write-Verbose "Selected CDR database, FQDN: $sqlSrvFqdn"
}
catch {
Write-Error "Unable to find the CDR database."
break
}
# Get the current logged on user
$currentLoggedOnUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# Define the SQL query from the parameter $CallDirection using switch
switch ($CallDirection) {
Inbound {$sqlQueryToRun = @"
use LcsCDR;
select
--SessionDetails users
User1.UserUri as User1Uri, User2.UserUri as User2Uri, StartedByUser.UserUri as StartedByUser,
--VoipDetails
--FromPhone.PhoneUri as FromPhoneUri, ConnectedPhone.PhoneUri as ConnectedPhoneUri,
--SessionDetails stats
SessionDetails.ResponseCode, SessionDetails.ResponseTime, SessionDetails.SessionEndTime,
DateDiff(ss,SessionDetails.ResponseTime, SessionDetails.SessionEndTime) as 'Call Duration',
--Client Versions
Client1Version.ClientType as User1ClientType, Client2Version.ClientType as User2ClientType
from SessionDetails
--VoipDetails
--join VoipDetails on SessionDetails.SessionIdTime = VoipDetails.SessionIdTime and SessionDetails.SessionIdSeq = VoipDetails.SessionIdSeq
--left outer join Phones as FromPhone on FromPhone.PhoneId = VoipDetails.FromNumberId
--left outer join Phones as ConnectedPhone on ConnectedPhone.PhoneId = VoipDetails.ConnectedNumberId
--Users
left outer join Users as User1 on User1.UserId = SessionDetails.User1Id
left outer join Users as User2 on User2.UserId = SessionDetails.User2Id
left outer join Users as StartedByUser on StartedByUser.UserId = SessionDetails.SessionStartedById
--Used to filter response group service calls only
left outer join ClientVersions as Client1Version on Client1Version.VersionId = SessionDetails.User1ClientVerId
left outer join ClientVersions as Client2Version on Client2Version.VersionId = SessionDetails.User2ClientVerId
where
--Filter response group service calls only
--Client1Version.ClientType = 1024 or
Client2Version.ClientType = 1024 and User2.UserUri not like '%+%'--'RTCC/4.0.0.0 Response_Group_Service'
order by ResponseTime desc
"@ }
Outbound {$sqlQueryToRun = @"
use LcsCDR;
select
--SessionDetails users
User1.UserUri as User1Uri, User2.UserUri as User2Uri, StartedByUser.UserUri as StartedByUser,
--VoipDetails
--FromPhone.PhoneUri as FromPhoneUri, ConnectedPhone.PhoneUri as ConnectedPhoneUri,
--SessionDetails stats
SessionDetails.ResponseCode, SessionDetails.ResponseTime, SessionDetails.SessionEndTime,
DateDiff(ss,SessionDetails.ResponseTime, SessionDetails.SessionEndTime) as 'Call Duration',
--Client Versions
Client1Version.ClientType as User1ClientType, Client2Version.ClientType as User2ClientType
from SessionDetails
--VoipDetails
--join VoipDetails on SessionDetails.SessionIdTime = VoipDetails.SessionIdTime and SessionDetails.SessionIdSeq = VoipDetails.SessionIdSeq
--left outer join Phones as FromPhone on FromPhone.PhoneId = VoipDetails.FromNumberId
--left outer join Phones as ConnectedPhone on ConnectedPhone.PhoneId = VoipDetails.ConnectedNumberId
--Users
left outer join Users as User1 on User1.UserId = SessionDetails.User1Id
left outer join Users as User2 on User2.UserId = SessionDetails.User2Id
left outer join Users as StartedByUser on StartedByUser.UserId = SessionDetails.SessionStartedById
--Used to filter response group service calls only
left outer join ClientVersions as Client1Version on Client1Version.VersionId = SessionDetails.User1ClientVerId
left outer join ClientVersions as Client2Version on Client2Version.VersionId = SessionDetails.User2ClientVerId
where
--Filter response group service calls only
--Client1Version.ClientType = 1024 or
Client1Version.ClientType = 1024 and User1.UserUri not like '%+%' and User2.UserUri like '%+%'--'RTCC/4.0.0.0 Response_Group_Service'
order by ResponseTime desc
"@}
}
# Try invoke the SQL query and catch any errors
try{
Write-Verbose "Invoking SQL Query on $sqlSrvFqdn"
$sqlInvoke = Invoke-Sqlcmd -ServerInstance $sqlSrvFqdn -Query $sqlQueryToRun
} catch {
Write-Error "Error invoking command on SQL Server: $sqlSrvFqdn. Please check FQDN and the current logged on user: $currentLoggedOnUser has permissions to access SQL Server."
break
} #end try
# Build the output based on the last x amount of months from $months
$sqlOutput = $sqlInvoke | Where-Object{($_.ResponseTime -gt (get-date).AddMonths(-$months))}
if($CallDirection -eq "Outbound"){
# Loop through the output and create a new PS object for each row with name and datetime
$sqlResult = foreach ($sqlOutputItem in $sqlOutput){
[PSCustomObject]@{
ResponseGroup = $sqlOutputItem.User1Uri
DateTime = $sqlOutputItem.ResponseTime
}
} # End of foreach
}else{
# Loop through the output and create a new PS object for each row with name and datetime
$sqlResult = foreach ($sqlOutputItem in $sqlOutput){
[PSCustomObject]@{
ResponseGroup = $sqlOutputItem.User2Uri
DateTime = $sqlOutputItem.ResponseTime
}
} # End of foreach
}
# Build the output by grouping the name and grabbing the count of each calls
$sqlResultCount = $sqlresult | Group-Object ResponseGroup | Sort-Object Count | Select-Object Name,Count
# Grab the last call entry for each response group
$sqlResultLastCalled = $sqlresult | Group-Object ResponseGroup | ForEach-Object{$_ | Select-Object -ExpandProperty Group | Select-Object -First 1} | Sort-Object DateTime
# Loop through the SQL result count and create new PS object for each row with name, last call date and count
Write-Verbose "Building output..."
$sqlAllResult = foreach ($sqlResultCountItem in $sqlResultCount){
$lastCall = $null
$lastCall = $sqlResultLastCalled | Where-Object{$_.ResponseGroup -eq $sqlResultCountItem.Name} | Select-Object -First 1 -Unique
Write-Verbose "Response Group name is: $($sqlResultCountItem.Name) and the last call is: $($lastCall.DateTime)"
[PSCustomObject]@{
ResponseGroupName = $sqlResultCountItem.Name
LastCallDate = $lastCall.DateTime
CallCount = $sqlResultCountItem.Count
}
} # End of foreach
Write-Verbose "Call records output built."
}
function Import-NasAACQData {
<#
.SYNOPSIS
Used to Build the Excel workbook from the RGS Configuration from Skype for Business.
.DESCRIPTION
Once you have the RGSConfig.zip (Unzip this to your chosen location) exported from Skype for Business, you can build the Excel workbook using the example command.
.EXAMPLE
Import-NasAACQData -rootFolder "C:\AACQ\RgsImportExport" -ffmpeglocation "C:\ffmpeg\bin\ffmpeg.exe" -TenantDomain "mytenant.onmicrosoft.com" -CQRAPrefix "ra_cq_" -AARAPrefix "ra_aa_" -cqReplacementSuffix "CQ" -aaReplacementSuffix "AA" -Verbose
#>
[CmdletBinding()]
param (
[Parameter()]
[string]$rootFolder,
[parameter()]
[switch]$interactive,
[parameter()]
[string]$ffmpeglocation,
[parameter()]
[string]$aaRAPrefix,
[parameter()]
[string]$cqRAPrefix,
[parameter()]
[string]$tenantDomain,
[Parameter()]
[switch]$skipAudio,
[parameter()]
[string]$cqNamePrefix,
[parameter()]
[string]$cqReplacementSuffix,
[parameter()]
[string]$aaNamePrefix,
[parameter()]
[string]$aaReplacementSuffix,
[Parameter(Mandatory=$true)]
[string]$logFolder
)
#Define Transcript Log Files
$logfile = (Get-Date).tostring("yyyyMMdd-hhmmss")
$transcriptfile = (New-Item -itemtype File -Path "$logfolder" -Name ("Import-NasAACQData-$logfile" + ".log"))
Start-Transcript -Path $transcriptfile
Write-Host "Transcript logging started $($transcriptfile)"
Write-Host "`n----------------------------------------------------------------------------------------------
`n TeamsAACQTools - Ash Ward - Nasstar
`n----------------------------------------------------------------------------------------------" -ForegroundColor Yellow
# Check Excel module is installed
Confirm-InstalledModule -Module ImportExcel -moduleName "ImportExcel module"
#$rootFolder = "C:\Users\Ash Ward\OneDrive - Modality Systems\Documents\Chris\RgsImportExport"
Write-Verbose "Importing queues from: $rootFolder\Queues.xml"
$Queues = Import-Clixml -Path "$rootFolder\Queues.xml" | Sort-Object name
Write-Verbose "Importing agent groups from: $rootFolder\AgentGroups.xml"
$AgentGroups = Import-Clixml -Path "$rootFolder\AgentGroups.xml" | Sort-Object name
Write-Verbose "Importing workflows from: $rootFolder\Workflows.xml"
$Workflows = Import-Clixml -Path "$rootFolder\Workflows.xml" | Sort-Object name
Write-Verbose "Importing business hours from: $rootFolder\HoursOfBusiness.xml"
$hours = Import-Clixml -Path "$rootFolder\HoursOfBusiness.xml"
# Let's grab the call records for the workflows
# Lets look at this for a later date, call count for each response group
# Will need to think how to do this without access to CDR database when offline from SfB environment
#Write-Verbose "Grabbing the call records from the CDR file"
#$workflowCDRExport = Export-ResponseGroupCallRecords -Months 3 -CallDirection Inbound
$ImportWorkflows = $Workflows | ForEach-Object{
Write-Verbose "Building workflow object: $($_.Name) - $($_.Identity.InstanceId.Guid)"
$fileLocation = ""
### Lets look at this for a later date, call count for each response group
### Will need to think how to do this without access to CDR database when offline from SfB environment
#$WorkflowCallCount, $WorkflowLastCallDate = $null
#$WorkflowCallCount = ($workflowCDRExport.where({$_.primaryuri.split(":")[1] -eq $_.ResponseGroupName})).CallCount
#Write-verbose "Call count = $workflowcallcount"
#$WorkflowLastCallDate = ($workflowCDRExport.where({$_.primaryuri.split(":")[1] -eq $_.ResponseGroupName})).LastCallDate
if($_.CustomMusicOnHoldFile.OriginalFileName){
Write-Verbose "TRUE: $($_.CustomMusicOnHoldFile.UniqueName)"
Write-Verbose "Importing custom music on hold file: $($_.CustomMusicOnHoldFile.OriginalFileName)"
$fileLocation = "\audio\{0}\{1}{2}" -f $_.Identity.InstanceId.Guid, $_.CustomMusicOnHoldFile.UniqueName, $_.CustomMusicOnHoldFile.OriginalFileName.substring($_.CustomMusicOnHoldFile.OriginalFileName.lastindexof("."))
}else{
Write-Verbose "No custom music on hold file specified, setting file location to null"
$fileLocation = ""
}
if($fileLocation -like "\*"){
Write-Verbose "Custom music on hold specified, setting default music on hold to false"
$UseDefaultMusicOnHold = "N"
}else{
Write-Verbose "No custom music on hold specified, setting default music on hold to true"
$UseDefaultMusicOnHold = "Y"
}
if($_.CustomMusicOnHoldFile.UniqueName){
Write-Verbose "Custom music on hold specified, setting file id"
$CustomMusicOnHoldFileID = $_.CustomMusicOnHoldFile.UniqueName
}else{
Write-Verbose "Custom music on hold not specified, setting to null"
$CustomMusicOnHoldFileID = ""
}
if($_.CustomMusicOnHoldFile.OriginalFileName){
Write-Verbose "Custom music on hold specified, setting filename"
$CustomMusicOnHoldFileName = $_.CustomMusicOnHoldFile.OriginalFileName
}else{
Write-Verbose "Custom music on hold not specified, setting filename to null"
$CustomMusicOnHoldFileName = ""
}
if($_.NonBusinessHoursAction.Uri){
if($_.NonBusinessHoursAction.Uri -like "sip:+*"){
Write-Verbose "Non business hours action target: $($_.NonBusinessHoursAction.Uri) is a phone number, converting to tel:+"
$e164num1 = $($_.NonBusinessHoursAction.Uri).substring(4).split("@")[0]
$NonBusinessHoursActionTargetUri = "tel:" + $e164num1
Write-Verbose "Non business hours action target converted: $NonBusinessHoursActionTargetUri"
}else{
Write-Verbose "$($_.NonBusinessHoursAction.Uri) not a phone number, passing value back"
if((Confirm-NasValidTarget -Target $_.NonBusinessHoursAction.Uri) -eq $True){
Write-Verbose "Importing non business hours action target: $($_.NonBusinessHoursAction.Uri)"
$NonBusinessHoursActionTargetUri = $_.NonBusinessHoursAction.Uri
}else{
Write-Verbose "Invalid non business hours action target: $($_.NonBusinessHoursAction.Uri)"
$NonBusinessHoursActionTargetUri = "Invalid Target"
}
}
}else{
Write-Verbose "No non business hours action target specified, setting value to null"
$NonBusinessHoursActionTargetUri = ""
}
if($_.DefaultAction.Uri){
if($_.DefaultAction.Uri -like "sip:+*"){
Write-Verbose "Default action target: $($_.DefaultAction.Uri) is a phone number, converting to tel:+"
$e164num2 = $($_.DefaultAction.Uri).substring(4).split("@")[0]
$DefaultActionTargetUri = "tel:" + $e164num2
Write-Verbose "Default action target converted: $DefaultActionTargetUri"
}else{
Write-Verbose "$($_.DefaultAction.Uri) not a phone number, passing value back"
if((Confirm-NasValidTarget -Target $_.DefaultAction.Uri) -eq $True){
Write-Verbose "Importing default action target: $($_.DefaultAction.Uri)"
$DefaultActionTargetUri = $_.DefaultAction.Uri
}else{
Write-Verbose "Invalid default action target: $($_.DefaultAction.Uri)"
$DefaultActionTargetUri = "Invalid Target"
}
}
}else{
Write-Verbose "No default action target specified, setting value to null"
$DefaultActionTargetUri = ""
}
if($_.DefaultAction.QueueID.InstanceId.Guid){
$DefaultActionQueueID = $_.DefaultAction.QueueID.InstanceId.Guid
}else{
Write-Verbose "No default action queue ID specified, setting value to null"
$DefaultActionQueueID = ""
}
if($_.DefaultAction.Question.element){
$DefaultActionQuestion = $_.DefaultAction.Question.element
}else{
Write-Verbose "No default action question specified, setting value to null"
$DefaultActionQuestion = ""
}
$defaultActionfileLocation = ""
if($_.DefaultAction.Prompt.AudioFilePrompt.OriginalFileName){
Write-Verbose "TRUE: $($_.DefaultAction.Prompt.AudioFilePrompt.OriginalFileName)"
Write-Verbose "Importing audio file: $($_.DefaultAction.Prompt.AudioFilePrompt.OriginalFileName)"
$defaultActionfileLocation = "\audio\{0}\{1}{2}" -f $_.Identity.InstanceId.Guid, $_.DefaultAction.Prompt.AudioFilePrompt.UniqueName, $_.DefaultAction.Prompt.AudioFilePrompt.OriginalFileName.substring($_.DefaultAction.Prompt.AudioFilePrompt.OriginalFileName.lastindexof("."))
}else{
Write-Verbose "No audio file specified, setting file location to null"
$defaultActionfileLocation = ""
}
if($_.DefaultAction.Prompt.AudioFilePrompt.UniqueName){
Write-Verbose "Audio file specified, setting file id"
$defaultActionAudioFileID = $_.DefaultAction.Prompt.AudioFilePrompt.UniqueName
}else{
Write-Verbose "Audio file not specified, setting to null"
$defaultActionAudioFileID = ""
}
if($_.DefaultAction.Prompt.AudioFilePrompt.OriginalFileName){
Write-Verbose "Audio file specified, setting filename"
$defaultActionAudioFilename = $_.DefaultAction.Prompt.AudioFilePrompt.OriginalFileName
}else{
Write-Verbose "Audio file not specified, setting filename to null"
$defaultActionAudioFilename = ""
}
if($_.DefaultAction.Prompt.TextToSpeechPrompt){
Write-Verbose "Text-to-speech specified, setting text-to-speech"
$defaultActionTextToSpeech = $_.DefaultAction.Prompt.TextToSpeechPrompt
}else{
Write-Verbose "Text-to-speech not specified, setting to null"
$defaultActionTextToSpeech = ""
}
$NonBusinessHoursActionfileLocation = ""
if($_.NonBusinessHoursAction.Prompt.AudioFilePrompt.OriginalFileName){
Write-Verbose "TRUE: $($_.NonBusinessHoursAction.Prompt.AudioFilePrompt.OriginalFileName)"
Write-Verbose "Importing audio file: $($_.NonBusinessHoursAction.Prompt.AudioFilePrompt.OriginalFileName)"
$NonBusinessHoursActionfileLocation = "\audio\{0}\{1}{2}" -f $_.Identity.InstanceId.Guid, $_.NonBusinessHoursAction.Prompt.AudioFilePrompt.UniqueName, $_.NonBusinessHoursAction.Prompt.AudioFilePrompt.OriginalFileName.substring($_.NonBusinessHoursAction.Prompt.AudioFilePrompt.OriginalFileName.lastindexof("."))
}else{
Write-Verbose "No audio file specified, setting file location to null"
$NonBusinessHoursActionfileLocation = ""
}
if($_.NonBusinessHoursAction.Prompt.AudioFilePrompt.UniqueName){
Write-Verbose "Audio file specified, setting file id"
$NonBusinessHoursActionAudioFileID = $_.NonBusinessHoursAction.Prompt.AudioFilePrompt.UniqueName
}else{
Write-Verbose "Audio file not specified, setting to null"
$NonBusinessHoursActionAudioFileID = ""
}
if($_.NonBusinessHoursAction.Prompt.AudioFilePrompt.OriginalFileName){
Write-Verbose "Audio file specified, setting filename"
$NonBusinessHoursActionAudioFilename = $_.NonBusinessHoursAction.Prompt.AudioFilePrompt.OriginalFileName
}else{
Write-Verbose "Audio file not specified, setting filename to null"
$NonBusinessHoursActionAudioFilename = ""
}
if($_.NonBusinessHoursAction.Prompt.TextToSpeechPrompt){
$NonBusinessHoursActionTTSPrompt = $_.NonBusinessHoursAction.Prompt.TextToSpeechPrompt
}else{
Write-Verbose "No non business hours Text to Speech specified, setting value to null"
$NonBusinessHoursActionTTSPrompt = ""
}
if($_.NonBusinessHoursAction.Question){
$NonBusinessHoursActionQuestion = $_.NonBusinessHoursAction.Question
}else{
Write-Verbose "No non business hours question specified, setting value to null"
$NonBusinessHoursActionQuestion = ""
}
if($_.NonBusinessHoursAction.QueueID.InstanceId.Guid){
$NonBusinessHoursQueueID = $_.NonBusinessHoursAction.QueueID.InstanceId.Guid
}else{
Write-Verbose "No non business hours queue ID specified, setting value to null"
$NonBusinessHoursQueueID = ""
}
if($_.LineUri){
$LineURI = $_.LineUri
}else{
Write-Verbose "No line uri specified, setting value to null"
$LineURI = $null
}
$_.Name = $_.Name.replace("_"," ")
# Let's create the 'cleaned' name, ready for the Teams import
Write-Verbose "Cleaning the imported name to remove special characters"
$CleanedWorkflowString = Remove-StringSpecialCharacter -String $_.Name -SpecialCharacterToKeep " "
#Null the vars before starting
$aaNameNoSpaces,$AutoAttendantName,$CleanedWorkflowSplit,$CleanedWorkflowLastWordRemoved,$CleanedWorkflowName = $null
# Remove the last word from the name as most have a suffix
if($_.Name -like "*queue" -or $_.Name -like "*RG" -or $_.Name -like "*(Q)" -or $_.Name -like "*RG Queue" -or $_.Name -like "* Q"){
$CleanedWorkflowSplit = $CleanedWorkflowString.Split(" ")
$CleanedWorkflowLastWordRemoved = [string]$CleanedWorkflowSplit[0..($CleanedWorkflowSplit.count-2)]
$CleanedWorkflowName = "{0}{1}" -f $($CleanedWorkflowLastWordRemoved -replace '\s+', ' ')," $aaReplacementSuffix"
# Need to clean, resource accounts need spaces removing
$ResourceAccountUPN = "{0}{1}@{2}" -f $AARAPrefix, $($CleanedWorkflowLastWordRemoved.Replace(" ","")), $($TenantDomain.Replace(" ",""))
}else{
$CleanedWorkflowName = "{0}{1}" -f $($CleanedWorkflowString -replace '\s+', ' ')," $aaReplacementSuffix"
$ResourceAccountUPN = "{0}{1}@{2}" -f $AARAPrefix, $($CleanedWorkflowString.Replace(" ","")), $($TenantDomain.Replace(" ",""))
}
if(!($AARAPrefix)){
#Set the resource account prefix
$AARAPrefix = "raaa-cc-lll-"
}