Sharepoint.ps1

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
using namespace Microsoft.Graph.PowerShell.Models
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='New*')]
param()
function Get-GraphSite                {
    <#
      .Synopsis
        Gets details of a sharepoint site, or its lists, drives or subsites
      .Description
        This interogates https://graph.microsoft.com/v1.0/sites/{id}
        which requires consent to use the Sites.Read.All scope or better.
        If no ID is provided it queries the Root site.
        Depending on the parameters given it will return subsites, lists
        detials of a single list, OneDrive Drives and on Note Notebooks.,
        it
      .Example
        >Get-GraphTeam -site | Get-GraphSite -Lists -Hidden
        Gets the site(s) for the current user's team(s) and gets lists
        from the site(s) including hidden ones.
    #>

    [cmdletbinding(DefaultParameterSetName="None")]
    param   (
        #Specifies a site, if omitted "root" will be assumed - the root site of the user's tennant.
        [Parameter( ValueFromPipeline=$true,Position=0)]
        $Site = "root",
        #If specified returns the lists in the site.
        [Parameter(Mandatory=$true, ParameterSetName="Lists")]
        [Switch]$Lists,
        #If specified returns the system lists which are hidden by default
        [Parameter(ParameterSetName="Lists")]
        [Parameter(Mandatory=$true, ParameterSetName="HiddenLists")]
        [Switch]$HIDdenLists,
        #if Specified returns the details of one list
        [Parameter(Mandatory=$true, ParameterSetName="SingleList")]
        [String]$ListID,
        #If Specified returns notebooks in the s
        [Parameter(Mandatory=$true, ParameterSetName="Notebooks")]
        [Switch]$Notebooks,
        #If Specified returns the drives in the site.
        [Parameter(Mandatory=$true, ParameterSetName="Drives")]
        [Switch]$Drives,
        #If Specified returns the sub-sites within the site, if the user has suitable permissions.
        [Parameter(Mandatory=$true, ParameterSetName="SubSites")]
        [Switch]$SubSites # Needs higher permissions
    )
    process {
        contexthas -WorkOrSchoolAccount -BreakIfNot
        foreach ($s in $site)    {
            if  ($s.id)          {$siteID    = $s.id}     else {$siteID = $s}
            if  ($s.weburl)      {$ParentURL = $s.weburl} else {
                $ParentURL = (Invoke-GraphRequest "$GraphUri/sites/$siteID").webUrl
            }
            if     ($ListID)     {
                Invoke-GraphRequest  "$GraphUri/sites/$SiteID/lists/$ListID/items?expand=fields" -valueOnly
            }
            elseif ($Lists -or $HIDdenLists)      {
                $Uri      =  "$GraphUri/sites/$SiteID/lists?expand=columns,contenttypes,drive"
                if ($HIDdenLists) {
                    $Uri += '&$select=system,createdDateTime,description,eTag,id,lastModifiedDateTime,name,webUrl,displayName,createdBy,lastModifiedBy,list'
                }
                $l = Invoke-GraphRequest $uri -valueOnly -PropertyNotMatch '@odata' -AsType ([MicrosoftGraphList])  |
                            Add-Member -PassThru -NotePropertyName siteID    -NotePropertyValue $siteID
                if ($ParentURL) {
                      $l |  Add-Member -PassThru -NotePropertyName ParentUrl -NotePropertyValue $ParentURL
                }
                else {$l}
            }
            elseif ($Drives)     {
                Invoke-GraphRequest -Uri  "$GraphUri/sites/$SiteID/drives" -valueOnly -AsType ([MicrosoftGraphDrive])
            }
            elseif ($SubSites)   {
                $SubSitelist = Invoke-GraphRequest  -Uri  "$GraphUri/sites/$SiteID/sites"  -valueOnly -AsType ([MicrosoftGraphSite]) |
                                      Add-Member -PassThru -NotePropertyName siteID -NotePropertyValue $siteID
                if ($ParentURL) {
                      $SubSitelist |  Add-Member -PassThru -NotePropertyName ParentUrl -NotePropertyValue $ParentURL
                }
                else {$SubSitelist}

            }
            elseif ($Notebooks)  {
                if ($siteID -eq "root") {$siteID  = (Invoke-GraphRequest  "$GraphUri/sites/root").id }
                $uri = "$GraphUri/sites/$siteID/onenote/notebooks?`$expand=sections"
                Invoke-GraphRequest -uri  $Uri -valueOnly -PropertyNotMatch '@odata' -AsType ([MicrosoftGraphNotebook]) }
            else                 {
                $uri = "$GraphUri/sites/$siteID`?expand=drives,lists,sites"
                $siteobj = Invoke-GraphRequest -Uri $uri -PropertyNotMatch '@odata' -AsType ([MicrosoftGraphSite])
                $siteobj.lists  | Add-Member -MemberType NoteProperty   -Name SiteID    -Value  $siteobj.id
                $siteobj.lists  | Add-Member -MemberType NoteProperty   -Name ParentUrl -Value  $siteobj.WebUrl
                $siteobj
            }
        }
    }
    #https://graph.microsoft.com/v1.0/sites?search=contoso
    #https://graph.microsoft.com/v1.0/sites/root/columns
    #https://graph.microsoft.com/v1.0/sites/root/contentTypes
}

function Get-GraphList                {
    <#
      .Synopsis
        Gets sharepoint list objects or their items
      .Description
        This interogates https://graph.microsoft.com/v1.0/sites/{id}/lists{id}
        which requires consent to use the Sites.Read.All scope or better.
        This does not suppor the use of a filter parameter so any "where"
        operation has to be done on the returned data.
      .Example
        >
        >$myTeamSite = Get-GraphTeam -Site | select -first 1
        >$problemsList = $myteamsite.lists | where name -like problem*
        >
        > Get-GraphList -list $problemslist -ColumnList
 
        The first command gets the current users group(s) and returns their site(s).
        For this example we select the first site. The sites returned by Get-GraphGroup /
        Get-GraphTeam have a .lists property and second command selects the list we want
        The third line shows calling Get-GraphList using the ID for both Site and List
        and getting the columns in the list.
        The next example shows an easier way to provide the information; and in fact
        there is already a .columns property of $problemsList which has the column information
      .Example
        > Get-graphlist $problemsList -Items
        This uses $problemsList from the previous example. Get-GraphGroup (aka Get-GraphTeam)
        gets the Site, it gets the sites lists, and adds the site ID as a property, so
        $Problemslist has propeties for the list ID and the site ID. So this exmaple uses a
        shorter form of just providing the list and returns the items in their raw state
      .Example
        > Get-graphlist $problemsList -Items -Property title, issuestatus, AssignedToLookupID, priority
        This builds on the previous example. Specifying -Property causes Get-GraphList to
        return the Item(s) Fields collection(s) and sets the default fields to be displayed.
        By default if an object has 4 visbible properties or fewer PowerShell displays it
        as a table, if it has more than 4 a list is used, this can be managed with
        $FormatEnumerationLimit. In this case 4 properties are show in a table view.
        However 'Person or Group' fields, like AssignedTo return a lookupID.
        This comes from the hidden list 'Users' and the next example shows how to get
        information from this list. (The Get-GraphSiteUserList provides a shortcut for geting
        this Information)
      .Example
        >
        >Get-GraphList -Site $myteamSite -Hidden | where name -eq 'users' |
            Get-Graphlist -Items -Property id,ContentType,Title,Name
 
        This uses the $myTeamSite variable from the first example.
        If neither Items, nor ColumnList is specified, Get-GraphList returns list objects,
        (the same result as using Get-GraphSite -Lists) so the first command gets lists
        in the team site including hidden ones - which aren't included in the .lists
        property of the site, and users IS hidden. The where command isolates that list,
        and it is piped into a second Get-GraphList command, which gets its items
        and displays the properties of interest
      .Example
        >
        >$mydocuments = Get-GraphUser -Site | Get-GraphSite -lists | where name -eq documents
        >Get-GraphList $shareddocsList -items | Select -expand driveItem |
              Copy-FromGraphFolder -Destination C:\temp
 
        This command works with a users "MySite" - the first command gets the user's
        site, gets its lists and selects the one named "Documents"
        The second gets the items in this list; when a list object has an associated drive,
        items returned by Get-GraphList -items will have a .DriveItem property.
        Driveitems can be piped into Copy-FromGraphFolder .
    #>

    [cmdletbinding(DefaultParameterSetName="ListID")]
    param   (
        #The list either as an ID or as a list object (which may contain the site.)
        [parameter(ValueFromPipeline=$true, ParameterSetName="ListID",       Position=0)]
        [parameter(ValueFromPipeline=$true, ParameterSetName="ListItems"    ,Position=0, Mandatory=$true)]
        [parameter(ValueFromPipeline=$true, ParameterSetName="ListIDColumns",Position=0, Mandatory=$true)]
        $List ,
        #Specifies a site, if omitted "root" will be assumed - the root site of the user's tennant.
        $Site = "root",
        #If specified returns hidden lists (like 'Users')
        [Parameter(ParameterSetName="ListofLists",Mandatory=$true)]
        [Switch]$HIDden,
        #If specified returns the list's items
        [Parameter(ParameterSetName="ListItems")]
        [Switch]$Items,
        #If specified returns the columns in the list
        [parameter(ParameterSetName="ListIDColumns", Mandatory=$true)]
        [Switch]$ColumnList,
        #if specified returned items will be expanded and the default display fields will be set
        [Parameter(ParameterSetName="ListItems")]
        [Alias('Fields')]
        [String[]]$Property
    )
    process {
        if     ($List.siteID) {$siteID = $List.siteID}
        elseif ($Site.id)     {$siteID = $Site.ID}
        else                  {$siteID = $Site}  #Site has a default, so won't be empty
        #Don't set listID if List is empty (it has no default)
        if     ($List.id)     {$listID = $List.ID}
        elseif ($List -is [string] -and  $list -match $GUIDRegex)   {
            $listID = $List
            if (-not $PSBoundParameters.ContainsKey('Site')) { #If we got a list ID and no site it's probably not the root!
                Write-Warning -Message 'Assuming root site. If a 404 "not found" error occurs specify the site explicitly.'
            }
        }
        elseif ($List -is [string]) {
            $listID = (Invoke-GraphRequest "$GraphUri/sites/$SiteID/lists?`$Select=ID,Displayname").value.where({$_.displayName -like $List}).id
            if (-not $listID -or $ListID.Count -gt 1) {
                Write-Warning "Could not resolve $List to a single list with the site information provided. "
            }
        }

        if     ($Items -or $Property) {
            $uri = "$GraphUri/sites/$siteID/lists/$listID/items?expand=fields"
            if ($List.drive.id) { $uri += ',driveItem' } #trying to expand driveItem in drive-less lists causes an error.
            Write-Progress -Activity 'Getting list items'
            $listitems = Invoke-GraphRequest -uri $uri -valueOnly -PropertyNotMatch '@odata'
            Write-Progress -Activity 'Getting list items' -Completed
            if ($Property) {
                $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$Property)
                $psStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
                foreach ($i in $listitems) {
                    [pscustomobject]$i.fields |
                    Add-Member  -PassThru    -MemberType MemberSet    -Name PSStandardMembers -Value $PSStandardMembers  |
                    Add-Member  -PassThru -NotePropertyName SiteID -NotePropertyValue $siteID  |
                    Add-Member  -PassThru -NotePropertyName ListID -NotePropertyValue $listID  |
                    Add-Member  -PassThru -NotePropertyName ItemID -NotePropertyValue $i.id
                }
                return
            }
            else {
                foreach ($i in $listitems) {
                    New-Object MicrosoftGraphListItem -Property $i |
                        Add-Member -PassThru -NotePropertyName SiteID -NotePropertyValue $siteID |
                        Add-Member -PassThru -NotePropertyName ListID -NotePropertyValue $listID
                }
                return
            }
        }
        #If we were asked for listItems we will have returned in the previous if. From here on we return objects for one or more list(s)
        elseif ($List)  {
            Write-Progress -Activity 'Getting list details'
            $uri = "$GraphUri/sites/$siteID/lists/$listID`?expand=columns,contenttypes,drive,items(expand=fields)"
            $result =  Invoke-GraphRequest -uri $uri -PropertyNotMatch '@odata'
            Write-Progress -Activity 'Getting list details' -Completed
        }
        else   {
            Write-Progress -Activity 'Getting Site Lists'
            $uri =  "$GraphUri/sites/$siteID/lists?expand=columns,contenttypes,drive"
            if ($HIDden) {$uri += '&$select=createdDateTime,description,eTag,id,lastModifiedDateTime,name,webUrl,displayName,createdBy,lastModifiedBy,list' }
            $result = Invoke-GraphRequest $uri -valueOnly -PropertyNotMatch '@odata'
            Write-Progress -Activity 'Getting Site Lists' -Completed
        }
        if     ($ColumnList) {
            foreach ($r in $result) {
                $listID   = $r.id
                $listName = $r.displayName
                foreach ($c in $r.columns) {
                    New-object MicrosoftGraphColumnDefinition -Property $c |
                        Add-Member -PassThru -NotePropertyName SiteID   -NotePropertyValue $siteID  |
                        Add-Member -PassThru -NotePropertyName ListID   -NotePropertyValue $listID  |
                        Add-Member -PassThru -NotePropertyName ListName -NotePropertyValue $listName
                }
            }
        }
        else   {
            foreach ($r in $result) {
             New-Object MicrosoftGraphList -Property $r |
                Add-Member -PassThru -NotePropertyName SiteID -NotePropertyValue $siteID
            }
        }
    }
}

<#
Update list item PATCH https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id} https://docs.microsoft.com/en-us/graph/api/listitem-update?view=graph-rest-1.0
 
Versions
GET /sites/{site-id}/items/{item-id}/versions
GET /sites/{site-id}/lists/{list-id}/items/{item-id}/versions
#>


function New-GraphList                {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PS', '')]

    <#
      .Synopsis
        Creates a new sharepoint list
      .Description
        This posts a new item to https://graph.microsoft.com/v1.0/sites/{id}/lists
        which requires consent to use the Sites.Manage.All scope.
        The API allows lists to be created - but not with content types, only as a defined
        collection of columns. There is no PATCH or DELETE support so there there are is
        no Set- or Remove- function to go with the New-
      .Example
        >$site = Get-GraphTeam -ByName Consultants -site
        >$textcolumndef = New-GraphTextColumn -TextType plain
        >$column1 = New-GraphColumn -Name Author -ColumnDefinition $textcolumndef
        >$numberColumnDef = New-GraphNumberColumn
        >$column2 = New-GraphColumn -Name PageCount -ColumnDefinition $numberColumnDef
        >$booksList = New-GraphList -Name NewBooks -Columns $column1,$column2 -Site $site -Template genericList
        >Start $bookslist.weburl
 
        This builds the example at https://docs.microsoft.com/en-us/graph/api/list-create?view=graph-rest-1.0
        The first line gets the sharepoint site for a team the current user is a member of named 'consultants'
        The second creates the column settings for a text column and the third builds a named column
        definition with that specification. Lines 4 and 5 define a Number column
        And line 6 creates a new generic list on the site found in line 1; the list is named 'books'
        and has columns title (as all generic list items do), Author and Page count (the latter two being
        defined in lines 2-5). The final line opens the new list in a browser.
      .Example
        >New-GraphList -Name books -Columns (ListColumn author (TextColumn)),(ListColumn pagecount (NumberColumn)) -Site $site
        This example does the same task as the previous one but leaves out some default parameters :
        text columns default to plain text and genericList is the default template.
        The columns are specifed using Aliases to give sort of DSL: "(listcolumn author (textColumn))" is eqivalent to
        (New-GraphColumn -Name Author -ColumnDefinition (New-TextColumn) )
      .Example
        >
        >$cols = 'AssignedTo', 'IssueStatus', 'TaskDueDate', 'V3Comments' | foreach {Get-GraphSiteColumn -name $_}
        >$cols += Get-GraphSiteColumn -Name 'priority' -ColumnGroup 'Core Task and Issue Columns'
        >New-GraphList -Name 'Problem Tracking' -Columns $cols -Site $site -Template genericList
 
        This gets a set of pre-existing columns and uses them to create a new list.
        The first line gets columns with unique names. "Priority" is defined in multiple groups,
        so the second line qualifies which version ot wants
        And the third line uses the columns to create a list.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        #The Name of the list
        [parameter(Mandatory=$true,Position=0)]
        [Alias('Name')]
        $DisplayName,
        #The site where the list is to be added either as an ID or as a site object containing an ID
        $Site,
        #The base list template used in creating the list. This is validated against typical list names, though you made need to modify the code to add others
        [ValidateSet('documentLibrary', 'genericList', 'tasks', 'survey', 'links', 'announcements', 'contacts')]
        [string]$Template = 'genericList',
        #A longer description for the list
        $Description ,
        #Columns to use in the list
        $Columns,
        #Create the list hidden
        [switch]$Hidden
    )
    if     ($Site.ID)           {$siteID = $Site.id}
    elseif ($site -is [string]) {$siteID = $site }
    else   {Write-Warning -Message 'Could not determine the site ID'; return}
    $WebParams = @{ 'URI'              = "$GraphUri/sites/$siteID/lists"
                    'Method'           = 'Post'
                    'ContentType'      = 'application/json'
                    'PropertyNotMatch' = '@odata'
                    'AsType'           = ([MicrosoftGraphList])
    }
    $settings  = @{
        'displayName'             = $DisplayName;
        'list'   = @{
            'contentTypesEnabled' = [bool]$ContentTypes;
            'hidden'              = [bool]$HIDden
            'template'            = $Template
        }
    }
    if ($Description) {
        $settings['description']  = $Description
    }
    if ($Columns) {
        $settings['columns']      = @() + $Columns
    }
    if ($ContentTypes) {
        $settings['contentTypes'] = @()
        $i = 1
        foreach ($ct in $contentTypes) {
            $ct['order'] = @{'position' = $i ; 'default' = ($i -eq 1) }
            $settings['contentTypes'] += $ct
         }
    }
    $WebParams['body'] = ConvertTo-Json $settings  -Depth 10
    Write-Debug $WebParams.body
    if ($Force -or $PSCmdlet.ShouldProcess($DisplayName,"Add list to site $($site.name)")) {
        Invoke-GraphRequest @WebParams |
            Add-Member -PassThru -NotePropertyName SiteID -NotePropertyValue $siteID
    }
}

function Add-GraphListItem            {
    <#
      .Synopsis
        Adds an item to a SharePoint List
      .Description
        This posts a new item to https://graph.microsoft.com/v1.0/sites/{id}/lists{id}/items
        which requires consent to use the Sites.ReadWrite.All scope
        Posting to a list is quite basic - it is a set of Name-ValuePairs and
        FIELD NAMES ARE CASE SENSITIVE. If you get a 400 error from the server the
        first thing to check is the names of the fields. It does not appear to be possible to
        post certain types of field - lookup and Person/Group being the major issues.
        The command will try to post what it is given, but it makes no attempt at validating it!
     .Example
     >
     >$myteamsite = Get-GraphTeam -Site |select -first 1
     >$problemslist = $myteamsite.lists.where({$_.name -like "problem*"})
     >Add-GraphListItem -List $problemslist -Fields @{Title='Demo Item';IssueStatus='Active';Priority='(2) Normal';}
 
     The first command gets a team site which has a list named "Problem reports"
     The second line gets that list
     The third creates a list item with Title, IssueStatus and Priority fields.
    #>

    [cmdletbinding(SupportsShouldProcess=$true)]
    param(
        #The list to add to; this can be an ID, or list object with an ID, and a site ID
        [parameter(Mandatory=$true,Position=0)]
        $List,
        #The item property values in a hash table as @{col1=$value1; col2='Value2'; col3=33}
        [parameter(Mandatory=$true,Position=1)]
        [hashtable]$Fields,
        #If the list parameter does not contain a .SiteID property allows the site to specified as an ID or object
        $Site,
        #If specified the new item will be returned, otherwise it is created silently.
        [Alias('PT')]
        [switch]$Passthru,
        #If specified the item will be added without prompting for confirmation (this is the default unless confirm preference is changed)
        [switch]$Force
    )
    if     ($List.siteid) {$siteID = $List.siteid}
    elseif ($Site.ID)     {$siteID = $Site.ID}
    elseif ($Site)        {$siteID = $Site}

    else   {throw 'The site could not be determined from the list; please specify the site explicitly.' ; return}
    if     ($List.id)     {$listID = $List.ID}
    else                  {$listID = $List}
    $webParams = @{
            'Method'      =  'Post'
            'URI'         =  "$GraphUri/sites/$siteID/lists/$listID/items"
            'ContentType' = 'application/json'
            'Body'        = (ConvertTo-Json @{'fields'=$Fields})
    }
    Write-Debug $webParams.Body
    if ($Force -or $PSCmdlet.ShouldProcess($List.name,'Add item')) {
        $result = Invoke-GraphRequest @webParams
        if ($Passthru) {
            $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$Fields.Keys)
            $psStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
            [pscustomobject]$result.fields |  Add-Member -MemberType MemberSet -Name PSStandardMembers -Value $PSStandardMembers -PassThru
                    Add-Member  -PassThru -NotePropertyName SiteID -NotePropertyValue $siteID  |
                    Add-Member  -PassThru -NotePropertyName ListID -NotePropertyValue $listID  |
                    Add-Member  -PassThru -NotePropertyName ItemID -NotePropertyValue $result.id
        }
    }
}

function Set-GraphListItem            {
    <#
      .Synopsis
        Updates an item in a SharePoint List
      .Description
        This Patches an existing item at https://graph.microsoft.com/v1.0/sites/{id}/lists{id}/items{id}/Fields
        which requires consent to use the Sites.ReadWrite.All scope
        Caveats in Add-GraphListItem apply to Set-GraphListItem.
      .link
        Add-GraphListItem
      .Example
      >
      >$problemitems = get-graphlist $problemslist -Items -Property title,issuestatus,AssignedToLookupID,priority
      >$problemitems[2] | Set-GraphListItem -Fields @{Priority='(2) Normal'}
 
      The first line gets the items from a list , and the second updates the Priority field of the third one
    #>

    [cmdletbinding(SupportsShouldProcess=$true)]
    param(
        #The item to update; this can be an ID or an object with an ID, and a list and site ID as well
        [parameter(ValueFromPipeline=$true, Mandatory=$true,Position=0)]
        $Item,
        #The item property values in a hash table as @{col1=$value1; col2='Value2'; col3=33}
        [parameter(Mandatory=$true,Position=1)]
        [hashtable]$Fields,
        #If the item does not contain the list, the list to delete from an ID, or list object with an ID, and a site ID
        $List,
        #If there is no site id in the item or list parameter allows the site to specified as an ID or object
        $Site,
        #If specified the item will be updated without prompting for confirmation
        [switch]$Force
    )
    process {
        foreach ($i in $i) {
            if     ($i.SiteId)    {$siteID = $i.SiteID}
            elseif ($List.siteid) {$siteID = $List.siteid}
            elseif ($Site.id)     {$siteID = $Site.id}
            elseif ($Site)        {$siteID = $Site}
            else   {throw 'The site could not be determined; please specify the site explicitly.' ; return}

            if     ($i.Listid)    {$listID = $i.ListID}
            elseif ($List.id)     {$listID = $List.ID}
            elseif ($listID)      {$listID = $List}
            else   {throw 'The List could not be determined; please specify the list explicity' ; return}
            if     ($i.Itemid)    {$i   = $i.ItemID}
            elseif ($i.id)        {$i   = $i.id}
            $webParams = @{
                    'Method'      = 'Patch'
                    'URI'         = "$GraphUri/sites/$siteID/lists/$listID/Items/$i/fields"
                    'ContentType' = 'application/json'
                    'Body'        =  ConvertTo-Json $Fields
            }
            Write-Debug $webParams.Body
            if ($Force -or $PSCmdlet.ShouldProcess($List.name,'Update item')) {
                $null = Invoke-GraphRequest @webParams
            }
        }
    }
}

function Remove-GraphListItem         {
    <#
      .Synopsis
        Deletes an item from a SharePoint List
      .Description
        This Deletes an item at https://graph.microsoft.com/v1.0/sites/{id}/lists{id}/items{id}
        which requires consent to use the Sites.ReadWrite.All scope
      .Example
        >
        >$problemitems = get-graphlist $problemslist -Items -Property title,issuestatus,AssignedToLookupID,priority
        >$problemitems[4] | Remove-GraphListItem
 
          The first line gets the items from a list , and the second line removes the fifth one
    #>


    [cmdletbinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
    param(
        #The item to remove; this can be an ID or an object with an ID, and a list and site ID as well
        [parameter(ValueFromPipeline=$true, Mandatory=$true,Position=0)]
        $Item,
        #If the item does not contain the list, the list to delete from an ID, or list object with an ID, and a site ID
        $List,
        #If there is no site id in the item or list parameter allows the site to specified as an ID or object
        $Site,
        #If specified the item will be deleted without prompting for confirmation (prompting is the default)
        [switch]$Force
    )
    Process {
        foreach ($i in $Item) {
            if     ($i.SiteID)    {$siteID = $i.SiteID}
            elseif ($List.SiteID) {$siteID = $List.siteid}
            elseif ($Site.id)     {$siteID = $Site.id}
            elseif ($Site)        {$siteID = $Site}
            else   {throw 'The site could not be determined; please specify the site explicitly.' ; return}

            if     ($i.ListID)    {$listID = $i.ListID}
            elseif ($List.id)     {$listID = $List.ID}
            elseif ($List)        {$listID = $List}
            else   {throw 'The List could not be determined; please specify the list explicity' ; return}

            if     ($i.ItemID)     {$i   = $i.ItemID}
            elseif ($i.id)         {$i   = $i.id}
            $webParams = @{
                    'Method'      =  'DELETE'
                    'URI'         =  "$GraphUri/sites/$siteID/lists/$listID/items/$i"
                    'ContentType' = 'application/json'
            }
            if ($force -or $PSCmdlet.ShouldProcess($i,'Delete List Item') ){ Invoke-GraphRequest @webParams }
        }
    }
}

function New-GraphColumn              {
    <#
      .synopsis
        Create a new Column definition for a sharepoint list
      .description
        New-GraphList uses column definitions to set up a new list.
        Each column has a name, description, default and one of the properties from the following list
        boolean, calculated, choice, currency, dateTime, lookup, number, personOrGroup or text
        Flags can also be set to say if the column is indexed, Readonly and/or required.
        Existing Columns defined in the site can be fetched with Get-GraphSiteColumn
        New-GraphColumn defines a new column to be included in a list, and a typical list will need
        multiple columns, which may be a mixture of new and existing columns.
        The specifics of each of the column types is handled by a new-{typeName}Column command.
        Examples appear in New-GraphList
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/columndefinition?view=graph-rest-1.0
      .link
        New-GraphList
    #>

    [CmdletBinding(DefaultParameterSetName='None')]
    [Alias('ListColumn')]
    param (
        [Parameter(Mandatory=$true,Position=0)]
        # The API-facing name of the column as it appears in the fields on a listItem. For the user-facing name, see displayName.
        [string]$Name,
        #A definition created with on of the New-*Column commands for a text, currency, boolean etc
        [Parameter(Mandatory=$true,Position=1)]
        [hashtable]$ColumnDefinition ,
        #For site columns, the name of the group this column belongs to. Helps organize related columns.
        [string]$ColumnGroup,
        #The user-facing description of the column.
        [string]$Description,
        #The user-facing name of the column.
        [string]$DisplayName,
        #Fills in the default value using a formula
        [Parameter(ParameterSetName='DefaultbyFormula',Mandatory=$true)]
        [string]$DefaultValueFormula,
        #Fills in the defaultt value using a fixed value
        [Parameter(ParameterSetName='DefaultbyValue',Mandatory=$true)]
        [string]$DefaultValueString ,
        #If specified the column is indexed to help the perfomance of searching and grouping.
        [bool]$Indexed,
        #Specifies whether the column values can be modified.
        [bool]$ReadOnly,
        # Specifies whether the column value is not optional.
        [bool]$Required,
        #If true, no two list items may have the same value for this column.
        [bool]$EnforceUniqueValues,
        # Specifies whether the column is displayed in the user interface.
        [boolean]$HIDden
    )
    $Settings = $ColumnDefinition + @{
                           'name'                = $Name ;
                           'indexed'             = [bool]$Indexed
                           'readOnly'            = [bool]$ReadOnly
                           'required'            = [bool]$Required
                           'enforceUniqueValues' = [bool]$EnforceUniqueValues
                           'hidden'              = [bool]$HIDden
    }

    if ($ColumnGroup) { $settings['columnGroup'] = $ColumnGroup }
    if ($Description) { $settings['description'] = $Description }
    if ($DisplayName) { $settings['displayName'] = $DisplayName }
    else              { $settings['displayName'] = $Name }
    if ($DefaultValueFormula) {
                        $settings['defaultValue']= @{'formula' = $DefaultValueFormula}
    }
    elseif ($DefaultValueString) {
                        $settings['defaultValue']= @{'value' = $DefaultValueString}
    }

    return $Settings
}

#region create all the column definitions used in a column
function New-GraphBooleanColumn       {
    <#
      .synopsis
        Creates a definition of a Sharepoint calculated column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/calculatedcolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('BooleanColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
    )

    return @{'boolean' = @{} }
}

function New-GraphCalculatedColumn    {
    <#
      .synopsis
        Creates a definition of a Sharepoint calculated column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/calculatedcolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('CalculatedColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        #The formula used to calculate the value.
        $Formula ,
        #Should the value be presented as a date only or a date and time
        [ValidateSet( 'dateOnly', 'dateTime')]
        $Format = 'dateTime',
        # Should the result be treated as Number, text, date, Currency or boolean
        [ValidateSet( 'boolean','currency','dateTime', 'number', 'text')]
        $OutputType = 'text'
    )
    $columnSettings = @{
        'formula'                        = $Formula
        'OutputType'                     = $OutputType
    }
    if ($OutputType -eq 'dateTime') {
        $columnSettings['format']        = $Format
    }
    return @{'calculated' = $columnSettings}
}

function New-GraphChoiceColumn        {
    <#
      .synopsis
        Creates a definition of a Sharepoint choice column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/lookupcolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('ChoiceColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        #The list of values available for this column..
        [Parameter(Mandatory=$true,Position=0)]
        [string[]]$Choices,
         #How the choices are to be presented in the UX, defaults to dropdown menu
        [ValidateSet('checkBoxes', 'dropDownMenu', 'radioButtons')]
        [string]$DisplayAs ='dropDownMenu',
        #Specified to indicates that values in the column should be able to exceed the standard limit of 255 characters.
        [switch]$AllowTextEntry
    )
    return @{'choice' =  @{
        'allowTextEntry'                 = [bool]$AllowTextEntry
        'choices'                        = @() + $Choices
        'displayAs'                      = $DisplayAs
    }}
}

function New-GraphCurrencyColumn      {
    <#
      .synopsis
        Creates a definition of a Sharepoint datetime column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/datetimecolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('CurrencyColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        $Locale = (Get-Culture)
    )

    if ($Locale -is [System.Globalization.CultureInfo] ) {
        return @{'currency' =  @{'locale' = $Locale.name }}
    }
    elseif ( [System.Globalization.CultureInfo]::GetCultureInfo($Locale).displayname -Notmatch 'Unknown' ) {
        return @{'currency' =   @{'locale' = $Locale}}
    }
    else {throw "$locale is not a known language"}
}

function New-GraphDateTimeColumn      {
    <#
      .synopsis
        Creates a definition of a Sharepoint datetime column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/datetimecolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('DateTimeColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        #Should the value be presented as a date only or a date and time
        [ValidateSet( 'dateOnly', 'dateTime')]
        $Format = 'dateTime',
        # Should the UX use default rendering or relative representation (eg. "today at 3:00 PM") or the standard absolute representation (eg. "5/10/2017 3:20 PM")
        [ValidateSet( 'default', 'friendly', 'standard')]
        $DisplayAs = 'default'
    )
    return @{'datetime' = @{
        'displayAs'                      = $DisplayAs
        'format'                         = $Format
      }  }
}

function New-GraphLookupColumn        {
    <#
      .synopsis
        Creates a definition of a Sharepoint lookup column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/lookupcolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('LookupColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        #The unique identifier of the lookup source list.
        [Parameter(Mandatory=$true,Position=0)]
        [string]$ListID,
        #The name of the lookup source column.
        [Parameter(Mandatory=$true,Position=0)]
        [string]$ColumnName,
        #If specified, this column is a secondary lookup, pulling an additional field from the list item looked up by the primary lookup. Use the list item looked up by the primary as the source for the column named here
        [string]$PrimaryLookupColumnID,
        #If Specified allows multiple/values to be specified
        [switch]$MultipleSelection,
        #Specified to indicates that values in the column should be able to exceed the standard limit of 255 characters.
        [switch]$AllowUnlimitedLength
    )
    $columnSettings = @{
        'allowMultipleValues'            = [bool]$MultipleSelection
        'allowUnlimitedLength'           = $AllowUnlimitedLength
        'columnName'                     = $ColumnName
        'listId'                         = $ListID
    }
    if ($IncludeGroups) {
          $columnSettings['primaryLookupColumnId'] = $PrimaryLookupColumnID
    }
    return @{'lookup' = $columnSettings}
}

function New-GraphNumberColumn        {
    <#
      .synopsis
        Creates a definition of a Sharepoint number column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/numbercolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('NumberColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        #How the value should be presented in the UX, number by default, the only other choice is percentage
        [ValidateSet('number', 'percentage')]
        $DisplayAs = 'number',
        #How many decimal places to display Auto, None, or the numbers one to five in words
        [ValidateSet('automatic', 'none', 'one', 'two', 'three', 'four', 'five')]
        [string]$DecimalPlaces = 'automatic',
        #Maximum permitted value
        [double]$Max,
        #Maximum permitted value
        [double]$Min
    )
    $columnSettings = @{
        'decimalPlaces'                 = $DecimalPlaces
        'displayAs'                     = $DisplayAs
    }
    if ($Max) {
        $columnSettings['maximum']      = $Max
    }
    if ($Min) {
        $columnSettings['minimum']      = $min
  }
    return @{'number' = $columnSettings}
}

function New-GraphPersonOrGroupColumn {
    <#
      .synopsis
        Creates a definition of a Sharepoint person or group column
      .link
        https://docs.microsoft.com/en-us/graph/api/resources/personorgroupcolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('PersonColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        #If Specified allows multiple/users to be specified
        [switch]$MultipleSelection,
        #Chooses how the name should be displayed; the default is to show name and presence, but it can first name, title, mail etc.
        [ValidateSet('Account', 'department firstName', 'id', 'lastName', 'mobilePhone', 'name', 'nameWithPictureAndDetails', 'nameWithPresence',
                      'office', 'pictureOnly36x36', 'pictureOnly48x48', 'pictureOnly72x72', 'sipAddress', 'title', 'userName', 'workEmail', 'workPhone.')]
        [string]$DisplayAs = 'nameWithPresence',
        #If Specified allows groups to be selected as well as users
        [switch]$IncludeGroups
    )
    $columnSettings = @{
        'allowMultipleSelection'            = [bool]$MultipleSelection
        'displayAs'                         = $DisplayAs
    }
    if ($IncludeGroups) {
          $columnSettings['chooseFromType'] = 'peopleAndGroups'
    }
    else {$columnSettings['chooseFromType'] = 'peopleOnly' }

    return @{'personOrGroup' = $columnSettings}
}

function New-GraphTextColumn          {
    <#
      .Synopsis
        Creates a definition of a sharepoint text column
      .link
      https://docs.microsoft.com/en-us/graph/api/resources/textcolumn?view=graph-rest-1.0
    #>

    [CmdletBinding()]
    [Alias('TextColumn')]
    [OutputType([System.Collections.Hashtable])]
    param (
        #Text is single line unless multiline is specified.
        [Switch]$MultiLine,
        #A new entry replaces exisitng text unless append is specified
        [Switch]$Append,
        #The type of text being stored - plain or richText (plain by default)
        [ValidateSet('plain','richText')]
        [string]$TextType = 'plain' ,
        #The maximum number of characters for the value.
        [int32]$MaxLength,
        #The size of the text box.
        [int32]$LinesForEditing
    )
    $columnSettings = @{
        'allowMultipleLines'                = [bool]$MultiLine
        'appendChangesToExistingText'       = [bool]$Append
        'textType'                          = $TextType
    }
    if ($MaxLength) {
        $columnSettings['maxLength']       = $MaxLength
    }
    if ($TextboxSize) {
        $columnSettings['linesForEditing'] = $TextboxSize
    }
    return  @{'text' = $columnSettings}
}
#endregion

function New-GraphContentType         {
    [cmdletbinding()]
    [OutputType([System.Collections.Hashtable])]
    param (
        #The ID of the contenttype
        [parameter(Mandatory=$true)]
        [string]$ParentID,
        #The name of the content type that the list will display
        [parameter(Mandatory=$true)]
        [string]$Name,
        # the content type cannot be modified unless this value is first set to false
        [Switch]$ReadOnly,
        # If Specified he content type cannot be modified by users or through push-down operations. Only site collection administrators can seal or unseal content types.
        [Switch]$Sealed
    )
    @{  'name'     = $Name
        'id'       = $ParentID
        'readOnly' = [bool]$ReadOnly
        'sealed'   = [bool]$Sealed
    }
}

function Get-GraphSiteColumn          {
    <#
      .synopsis
        Gets a column which is defined for the whole site.
    #>

    [cmdletbinding(DefaultParameterSetName='None')]
    param (
    #Selects column(s) by name (and possibly group)
    [Parameter(ParameterSetName='Terms',Position=0, ValueFromPipeline=$true)]
    [String]$Name = '*',
    #Selects column(s) by group (and possibly by name)
    [Parameter(ParameterSetName='Terms',Position=1)]
    [String]$ColumnGroup,
    #Selects a column by unique ID
    [Parameter(ParameterSetName='Terms',Position=2)]
    [string]$ID,
    #Allows a custom where clause instead of Name and/or group and/or ID
    [Parameter(ParameterSetName='WhereClause')]
    [scriptblock]$Where,
    <#Get-GraphSiteColumn is intended to return one column to used when creating a new list, so
    if multiple columns are returned that would be an error (i.e. two columns have the
    same name and group wasn't given.) If -allowMultiple is specified it is *not* treated as an error #>

    [switch]$AllowMultiple,
    [switch]$Raw
    )
    begin {
        # $filter doesn't work on /sites/root/columnd
        if (-not $Script:RootSiteColumns) {
            Write-Progress -Activity "Getting list of columns for the root site"
            $Script:RootSiteColumns = Invoke-GraphRequest -Method Get -Uri "$GraphUri/sites/root/columns" -valueOnly
            Write-Progress -Activity "Getting list of columns for the root site" -Completed
        }
    }
    process {
        if (-not $Where) {
            $whereText = ''
                if ($id)           {$whereText += "`$_.id -eq '$id' -and" }
                if ($ColumnGroup)  {$whereText += "`$_.ColumnGroup -like '$ColumnGroup' -and"}
                if ($Name)         {$whereText += "(`$_.Name -like '$Name' -or `$_.displayname -like '$Name')"}
                $wheretext = $whereText -replace ' -and$',''
                $where     = [scriptblock]::Create("$whereText")
        }
        $result = $Script:RootSiteColumns.where($where)
        if ($result.count -gt 1 -and -not $AllowMultiple) {throw 'More than one result was found and -AllowMultiple was not specified'}
        elseif ($raw) {return $result}
        else          {
            $result | ForEach-Object{
                New-Object -TypeName MicrosoftGraphColumnDefinition -Property $_
            }
        }
    }
}

function Get-GraphSiteUserList        {
    <#
      .Synopsis
        Gets the Users list for a [team] site
    #>

    [cmdletbinding()]
    param (
        #The [team] Site whose user-list will be fetched
        [parameter(ValueFromPipeline=$true,Position=0,Mandatory=$True)]
        $Site
    )    #If we get a list where it should be a site, but it has a site ID ... use that.
    if ($site.siteid) {$site=$site.Siteid}
    Write-Progress -Activity 'Getting Site Users' -CurrentOperation 'Finding list'
    $list = Get-GraphSite -HiddenLists -Site $Site   | Where-Object name -eq 'users'
    Write-Progress -Activity 'Getting Site Users' -CurrentOperation 'Getting users'
    $usersAndGroups = Get-Graphlist -List $list -Items -Property id,contenttype,title,name
    Write-Progress -Activity 'Getting Site Users' -Completed
    $usersAndGroups.where({$_.contentType -eq 'person' -and  $_.name -match "@"}) |
        Select-Object -Property id, Title, @{n='Account';e={$_.name -replace '^.*\|',''}}, Name
}