PureStorage.FlashArray.VMware.VCF.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
function Initialize-PfaVcfWorkloadDomain {
  <#
  .SYNOPSIS
    Configures a workload domain for Pure Storage
  .DESCRIPTION
    Configures FlashArray host group, provisions vVol Protocol Endpoint or VMFS datastore, configures iSCSI (if needed), preps ESXi hosts, validates and commissions hosts in VCF SDDC Manager.
  .INPUTS
    FQDNs or IPs of each host, valid credentials, a FlashArray FQDN and credentials, protocol choice, a datastore name and size OR protocol endpoint.
  .OUTPUTS
    Returns host group.
  .NOTES
    Version: 2.0
    Author: Cody Hosterman https://codyhosterman.com
    Creation Date: 10/02/2020
    Purpose/Change: Core support
  .EXAMPLE
    PS C:\ $faCreds = get-credential
    PS C:\ $esxiCreds = get-credential
    PS C:\ Initialize-PfaVcfWorkloadDomainTest -EsxiHostFqdn "esxi-02.purecloud.com","esxi-04.purecloud.com" -esxihostcredential $esxiCreds -Protocol iSCSI -Vvol -FlashArrayFqdn flasharray-m20-1 -FlashArrayCredential $facreds -vcfnetworkpool iSCSI-vVols
     
    Configures and commissions hosts for inclusion in a iSCSI vVol Principal Workload Domain.
    .EXAMPLE
    PS C:\ $faCreds = get-credential
    PS C:\ $esxiCreds = get-credential
    PS C:\ Initialize-PfaVcfWorkloadDomainTest -EsxiHostFqdn "esxi-02.purecloud.com","esxi-04.purecloud.com" -esxihostcredential $esxiCreds -FlashArrayFqdn flasharray-m20-1 -FlashArrayCredential $facreds -vcfnetworkpool iSCSI-vVols -datastoreName "vcftest" -sizeInTB 16 -Protocol fc
     
    Configures and commissions hosts for inclusion in a FC VMFS Principal Workload Domain.
  .EXAMPLE
    PS C:\ $faCreds = get-credential
    PS C:\ $esxiCreds = get-credential
    PS C:\ $allHosts = @()
    PS C:\ Import-Csv C:\hostList.csv | ForEach-Object {$allHosts += $_.hostnames}
    PS C:\ Initialize-PfaVcfWorkloadDomainTest -EsxiHostFqdn $allHosts-esxihostcredential $esxiCreds -Protocol iSCSI -Vvol -FlashArrayFqdn flasharray-m20-1 -FlashArrayCredential $facreds -vcfnetworkpool iSCSI-vVols
     
    Configures and commissions hosts for inclusion in a iSCSI vVol Principal Workload Domain using a CSV source file with a column heading of hostnames.
 
  *******Disclaimer:******************************************************
  This scripts are offered "as is" with no warranty. While this
  scripts is tested and working in my environment, it is recommended that you test
  this script in a test lab before using in a production environment. Everyone can
  use the scripts/commands provided here without any written permission but I
  will not be liable for any damage or loss to the system.
  ************************************************************************
  #>


  [CmdletBinding()]
  Param(

      [Parameter(Position=0,mandatory=$true)]
      [string[]]$EsxiHostFqdn,

      [Parameter(Position=1,ValueFromPipeline=$True,mandatory=$true)]
      [System.Management.Automation.PSCredential]$EsxiHostCredential,

      [Parameter(Position=3,mandatory=$true,ParameterSetName='VMFS')]
      [string]$DatastoreName,

      [Parameter(Position=4,ParameterSetName='VMFS')]
      [int]$SizeInGB,

      [Parameter(Position=5,ParameterSetName='VMFS')]
      [int]$SizeInTB,

      [Parameter(Position=6)]
      [ValidateSet('iSCSI','FC')]
      [string]$Protocol,

      [Parameter(Position=7,mandatory=$true,ParameterSetName='vVol')]
      [switch]$Vvol,

      [Parameter(Position=8,mandatory=$True)]
      [string]$FlashArrayFqdn,

      [Parameter(Position=9,mandatory=$true)]
      [System.Management.Automation.PSCredential]$FlashArrayCredential,

      [Parameter(Position=10,mandatory=$true)]
      [string]$VcfNetworkPool
    
  )
  Import-Module PureStoragePowerShellSDK
  try {
    Get-InstalledModule -Name PowerVCF -ErrorAction Stop |Out-Null
  }
  catch {
    throw "Please install PowerVCF with install-module PowerVCF."
  }
  if ($null -eq $global:sddcManager)
  {
    throw "Please connect to SDDC Manager with Request-VcfToken."
  }
  if ($psversiontable.PSEdition -ne "Core")
  {
    throw "The cmdlet Initialize-PfaVcfWorkloadDomain is only supported with PowerShell Core (7.x or later)."
  }
  if ($Protocol -eq "iSCSI" -and ($Vvol -ne $True))
  {
    throw "iSCSI can only be specified with vVols. VMFS can only be principal storage when deployed with Fibre Channel."
  }
  Write-Progress -id 1 -Activity "VCF and Pure ESXi Host Commission Process" -Status "Verifying input" -PercentComplete 5
  $ErrorActionPreference = "stop"
  if ($Vvol -ne $true)
  {
    if (($sizeInGB -eq 0) -and ($sizeInTB -eq 0))
    {
        throw "Please enter a size in GB or TB"
    }
    elseif (($sizeInGB -ne 0) -and ($sizeInTB -ne 0)) {
        throw "Please only enter a size in TB or GB, not both."
    }
    elseif ($sizeInGB -ne 0) {
        $volSize = $sizeInGB * 1024 *1024 *1024   
    }
    else {
        $volSize = $sizeInTB * 1024 *1024 *1024 * 1024
    }
  }
  Write-Progress -id 1 -Activity "VCF and Pure ESXi Host Commission Process" -Status "Connecting to Resources" -PercentComplete 10
  Write-Progress -parentid 1 -Id 2 -Activity "Connecting to FlashArray" -Status "Connecting to $($FlashArrayFqdn)" -PercentComplete 50
  $flasharray = New-PfaArray -EndPoint $FlashArrayFqdn -Credentials $FlashArrayCredential -IgnoreCertificateError
  if ($Vvol -eq $true)
  {
    $arrayInfo = New-PfaRestOperation -resourceType array -restOperationType GET -flasharray $flasharray -SkipCertificateCheck
    if ($arrayInfo.version -eq "5.3.9")
    {
      throw "Found Purity 5.3.9--this is not a supported release for vVols with VCF. Please reach out to Pure Support to upgrade Purity to 5.3.10 or higher."
    }
    if (($arrayinfo.version.split(".")[0] -eq "5") -and ($arrayinfo.version.split(".")[1] -lt 3))
    {
      throw "Found a Purity release earlier than 5.3.x (currently at $($arrayinfo.version)). Please reach out to Pure Support to upgrade Purity to 5.3.x or higher."
    }
  }
  if ([string]::IsNullOrWhiteSpace($Protocol))
  {
    $foundProtocol = checkFaProtocol -flasharray $flasharray -ErrorAction stop
  }
  else {
    $foundProtocol = checkFaProtocol -flasharray $flasharray -protocol $Protocol -ErrorAction stop
  }
  Write-Debug -Message $foundProtocol
  $vcfpools = Get-VCFNetworkPool
  Write-Debug -Message ($vcfpools| out-string)
  if (($vcfpools.name -contains $VcfNetworkPool) -ne $true)
  {
    throw "Invalid VCF network pool ($($vcfnetworkpool)). Please verify network pools with Get-VCFNetworkPool"
  }
  else {
    $vcfNetworkInfo = Get-VCFNetworkIPPool -id ($vcfpools |Where-Object {$_.name -eq $VcfNetworkPool}).id
    Write-Debug -Message ($vcfNetworkInfo| out-string)
    if ($foundProtocol -eq "iSCSI")
    {
      if (($vcfNetworkInfo.type -contains "iSCSI") -eq $false)
      {
        throw "The specified network pool $($VcfNetworkPool) does not have an iSCSI-type vLAN assigned to it. Please add one or choose a network pool that does. This is required for iSCSI-vVols deployment."
      }
    }
    if (($vcfNetworkInfo.type -contains "VMOTION") -eq $false)
    {
      throw "The specified network pool $($VcfNetworkPool) does not have a VMOTION-type vLAN assigned to it. Please add one or choose a network pool that does. This is required for any deployment type."
    }
  }
  Write-Progress -parentid 1 -Id 2 -Activity "Connecting to FlashArray" -Status "Connected to $($FlashArrayFqdn)" -PercentComplete 100
  $esxiConnections = @()
  for ($i =0;$i -lt $EsxiHostFqdn.count;$i++)
  {
    Write-Progress -parentid 1 -Id 2 -Activity "Connecting to ESXi hosts" -Status "Connecting to $($EsxiHostFqdn[$i])" -PercentComplete ($i/$EsxiHostFqdn.count)
    $esxiConnections += connect-viserver -Server $EsxiHostFqdn[$i] -Credential ($EsxiHostCredential) -ErrorAction Stop
  }
  Write-Progress -parentid 1 -Id 2 -Activity "Connecting to ESXi hosts" -Status "Connected to $($EsxiHostFqdn.Count) ESXi hosts" -PercentComplete 100
  $faHosts = @()
  Write-Progress -id 1 -Activity "VCF and Pure ESXi Host Commission Process" -Status "Configuring storage connection for ESXi hosts" -PercentComplete 30
  for ($i =0;$i -lt $esxiConnections.count;$i++)
  {
    Write-Progress -parentid 1 -Id 2 -Activity "Configuring ESXi hosts on FlashArray" -Status "Configuring $($esxiConnections[$i].name)" -PercentComplete ($i/$esxiConnections.count)
    $foundHost = $null
    $foundHost = Get-PfaHostFromVmHost -esxi (get-vmhost $esxiConnections[$i].name) -Flasharray $flasharray -ErrorAction SilentlyContinue
    if ($null -ne $foundHost)
    {
      if ($null -ne $foundHost.hgroup)
      {
        throw "The host $($esxiConnections[$i].name) is already in a host group on the FlashArray. Please ensure it is not in-use and remove it from the group named $($foundHost.hgroup) ."
      }
      if ($foundprotocol -eq "iSCSI") 
      {
          if (0 -ne $foundHost[0].wwn.count)
          {
            throw "The host $($esxiConnections[$i].name) is already configured on the FlashArray for FC. Mixed mode is not supported by VMware."
          }
      }
      else 
      {
          if (0 -ne $foundHost[0].iqn.count)
          {
            throw "The host $($esxiConnections[$i].name) is already configured on the FlashArray for iSCSI. Mixed mode is not supported by VMware."
          }
      }
      $faHosts += $foundHost.name
    }
    else {
      if ($foundProtocol -eq "iSCSI")
      {
        $faHosts += (New-PfaHostFromVmHost -esxi (get-vmhost $esxiConnections[$i].name) -Iscsi -Flasharray $flasharray -ErrorAction Stop).name 
      }
      elseif ($foundProtocol -eq "FC") {
        $faHosts += (New-PfaHostFromVmHost -esxi (get-vmhost $esxiConnections[$i].name) -FC -Flasharray $flasharray -ErrorAction Stop).name  
      }
    }
  }
  Write-Debug -Message ($faHosts| out-string)
  $groupName = ("VCF-WorkloadDomain-" + (get-random -Maximum 9999 -Minimum 1000))
  $hostGroup = New-PfaRestOperation -resourceType "hgroup/$($groupName)" -restOperationType POST -flasharray $flasharray -SkipCertificateCheck  -ErrorAction stop
  if ($fahosts.count -gt 0)
  {
    if ($fahosts.count -gt 1)
    {
      $hostsJson = $fahosts |ConvertTo-Json
    }
    else {
      $hostsJson = ("[" + ($fahosts |ConvertTo-Json) + "]")
    }
    $hostGroup = New-PfaRestOperation -resourceType "hgroup/$($groupName)" -restOperationType PUT -flasharray $flasharray -jsonBody "{`"addhostlist`":$($hostsJson)}" -SkipCertificateCheck  -ErrorAction stop 
    Write-Debug -Message $hostGroup
  }
  Write-Progress -parentid 1 -Id 2 -Activity "Configuring ESXi hosts on FlashArray" -Status "Configured $($esxiConnections.count) hosts on FlashArray" -PercentComplete 100
  Write-Progress -id 1 -Activity "VCF and Pure ESXi Host Commission Process" -Status "Configuring physical storage." -PercentComplete 50
  if (![string]::IsNullOrWhiteSpace($DatastoreName))
  {
    Write-Progress -parentid 1 -Id 2 -Activity "Provisioning a VMFS datastore from the FlashArray." -Status "Creating Volume" -PercentComplete 25
    $newVol = New-PfaRestOperation -resourceType "volume/$($datastoreName)" -restOperationType POST -flasharray $flasharray -jsonBody "{`"size`":`"$($volSize)`"}" -SkipCertificateCheck -ErrorAction Stop 
    Write-Debug -Message $newVol
    New-PfaRestOperation -resourceType "hgroup/$($groupName)/volume/$($newVol.name)" -restOperationType POST -flasharray $flasharray -SkipCertificateCheck -ErrorAction Stop |Out-Null
    $newNAA =  "naa.624a9370" + $newVol.serial.toLower()
    $esxi = $esxiConnections |Select-Object -Last 1
    Write-Progress -parentid 1 -Id 2 -Activity "Provisioning a VMFS datastore from the FlashArray." -Status "Rescanning HBAs" -PercentComplete 50
    get-vmhost $esxi.name |Get-VMHostStorage -RescanAllHba  |Out-Null
    Write-Progress -parentid 1 -Id 2 -Activity "Provisioning a VMFS datastore from the FlashArray." -Status "Formatting VMFS" -PercentComplete 75
    get-vmhost $esxi.name |new-datastore -name $datastoreName -vmfs -Path $newNAA -FileSystemVersion 6 -ErrorAction Stop |Out-Null
    Write-Progress -parentid 1 -Id 2 -Activity "Provisioning a VMFS datastore from the FlashArray." -Status "Complete." -PercentComplete 100
  }
  else {
    Write-Progress -parentid 1 -Id 2 -Activity "Provisioning a vVol protocol endpoint from the FlashArray." -Status "Creating PE" -PercentComplete 25
    $protocolEndpoint = "vVol-Protocol-Endpoint"    
    New-PfaRestOperation -resourceType volume/$($protocolEndpoint)?protocol_endpoint=true -restOperationType POST -flasharray $flasharray -SkipCertificateCheck -ErrorAction SilentlyContinue |Out-Null
    try
    {
      Write-Progress -parentid 1 -Id 2 -Activity "Provisioning a vVol protocol endpoint from the FlashArray." -Status "Connecting PE" -PercentComplete 75
      New-PfaRestOperation -resourceType "hgroup/$($groupName)/volume/$($protocolEndpoint)" -restOperationType POST -flasharray $flasharray -SkipCertificateCheck -ErrorAction Stop |Out-Null
    }
    catch
    {
      if ($_.Exception -notlike "*Connection already exists.*")
      {
          throw $_.Exception
      }
    }
  }
  Write-Progress -id 1 -Activity "VCF and Pure ESXi Host Commission Process" -Status "Final Host Configuration" -PercentComplete 70
  foreach ($esxiConnection in $esxiConnections)
  {
      Write-Progress -parentid 1 -Id 2 -Activity "Configuring ESXi hosts." -Status "Enabling SSH on $($esxiConnections.count) hosts" -PercentComplete 25
      #prepare for VCF commissioning
      $esxi = get-vmhost $esxiConnection.name
      $esxi|Get-VMHostService |Where-Object { $_.Key -eq "TSM-SSH"} |Start-vmhostService |Out-Null
      Write-Progress -parentid 1 -Id 2 -Activity "Rescanning all hosts." -Status "Rescanning $($esxiConnections.count) hosts" -PercentComplete 50
      $esxi | Get-VMHostStorage -RescanAllHba  |Out-Null
      Write-Progress -parentid 1 -Id 2 -Activity "Rescanning all hosts." -Status "Complete" -PercentComplete 100
  } 
  if ($Vvol -eq $true)
  {
    Write-Progress -parentid 1 -Id 2 -Activity "Registering VASA Provider with VCF SDDC Manager." -Status "Adding VASA Provider" -PercentComplete 25
    $foundProviders = Get-PfaVcfVasaProvider
    $mgmtIP = New-PfaRestOperation -resourceType network -restOperationType GET -flasharray $flasharray -SkipCertificateCheck |Where-Object {$_.name -like "CT0.eth0"}
    $foundProvider = $foundProviders |Where-Object {$_.url -like "*$($mgmtIP.address)*"} 
    Write-Progress -parentid 1 -Id 2 -Activity "Registering VASA Provider with VCF SDDC Manager." -Status "Adding VASA Provider" -PercentComplete 50
    if ([string]::IsNullOrWhiteSpace($foundProvider))
    {
      New-PfaVcfVasaProvider -arrayAddress $FlashArrayFqdn -ArrayCredential $FlashArrayCredential -Protocol $foundProtocol |Out-Null
    }
    else {
     if ($foundProvider.storageContainers.protocolType -ne $foundProtocol)
     {
        Write-Warning -Message "The VASA provider for this array is already registered but the storage container is already registered with $($foundProtocol). VCF only allows a storage container to be registered via one protocol at a time."
     }
    }
    Write-Progress -parentid 1 -Id 2 -Activity "Registering VASA Provider with VCF SDDC Manager." -Status "Added VASA Provider" -PercentComplete 100
  }
  $hostSpecs = @()
  Write-Progress -id 1 -Activity "VCF and Pure ESXi Host Commission Process" -Status "Commissioning Hosts" -PercentComplete 85
  Write-Progress -parentid 1 -Id 2 -Activity "Generating JSON for host validation." -Status "Generating" -PercentComplete 25
  foreach ($EsxiHost in $EsxiHostFqdn)
  {
    $hostspec = New-Object -TypeName psobject
    $hostspec | Add-Member -MemberType NoteProperty -Name fqdn -value $EsxiHost
    $hostspec | Add-Member -MemberType NoteProperty -Name username -value $EsxiHostCredential.UserName
    if ($Vvol -eq $true)
    {
      $hostspec | Add-Member -MemberType NoteProperty -Name storageType -value "VVOL"
    }
    else {
      $hostspec | Add-Member -MemberType NoteProperty -Name storageType -value "VMFS_FC"
    }
    $hostspec | Add-Member -MemberType NoteProperty -Name password -value ($EsxiHostCredential.Password |ConvertFrom-SecureString -AsPlainText)
    $hostspec | Add-Member -MemberType NoteProperty -Name networkPoolName -value $VcfNetworkPool
    $hostspec | Add-Member -MemberType NoteProperty -Name networkPoolId -value ($vcfpools |Where-Object {$_.name -eq $VcfNetworkPool}).id
    if ($Vvol -eq $true)
    {
      $hostspec | Add-Member -MemberType NoteProperty -Name vvolStorageProtocolType -value $foundProtocol.ToUpper()
    }
    $hostSpecs += $hostspec
  } 
  Write-Progress -parentid 1 -Id 2 -Activity "Generating JSON for host validation." -Status "Generated" -PercentComplete 100
  $hostJson =  $hostSpecs  |ConvertTo-Json
  Write-Debug -Message $hostJson
  #refresh VCF connection
  $headers = @{"Accept" = "application/json"}
  $response = Invoke-RestMethod -Method PATCH -Uri "https://$($sddcManager)/v1/tokens/access-token/refresh" -Headers $headers -body $global:refreshToken -SkipCertificateCheck
  $Global:accessToken = $response
  $vcfHeader = @{authorization="Bearer $($Global:accessToken)"}
  #validate host configuration
  Write-Progress -parentid 1 -Id 2 -Activity "Adding hosts to SDDC Manager" -Status "Submitting for validation." -PercentComplete 5
  $hostValidationTask = Invoke-RestMethod -Method POST -URI "https://$($sddcManager)/v1/hosts/validations"  -ContentType application/json -headers $vcfHeader -body $hostJson -SkipCertificateCheck
  Do 
  {
      Write-Progress -parentid 1 -Id 2 -Activity "Adding hosts to SDDC Manager." -Status "Waiting for validation" -PercentComplete 25
      $hostValidationTaskResponse = Invoke-RestMethod -Method GET -URI "https://$($sddcManager)/v1/hosts/validations/$($hostValidationTask.id)" -Headers $vcfHeader -ContentType application/json -SkipCertificateCheck
      Start-Sleep -Seconds 5
  }
  While ($hostValidationTaskResponse.executionStatus -eq "IN_PROGRESS")
  Write-Debug -Message $hostValidationTaskResponse
  Write-Progress -parentid 1 -Id 2 -Activity "Adding hosts to SDDC Manager." -Status "Validated" -PercentComplete 45
  if ($hostValidationTaskResponse.executionStatus -eq "COMPLETED" -and $hostValidationTaskResponse.resultStatus -eq "SUCCEEDED") 
  {
      Write-Progress -parentid 1 -Id 2 -Activity "Adding hosts to SDDC Manager." -Status "Commissioning" -PercentComplete 50
      $commissionHostsTask = Invoke-RestMethod -Method POST -URI "https://$sddcManager/v1/hosts/" -headers $vcfHeader -ContentType application/json -body $hostJson -SkipCertificateCheck
  }
  else {
      throw "There was a problem validating the hosts: $($hostValidationTaskResponse.validationChecks.errorResponse.message)"
  }
  Do 
  {
    Write-Progress -parentid 1 -Id 2 -Activity "Adding hosts to SDDC Manager." -Status "Waiting for commissioning to complete" -PercentComplete 75
      $hostCommissionTaskResponse = Invoke-RestMethod -Method GET -URI "https://$($sddcManager)/v1/tasks/$($commissionHostsTask.id)" -Headers $vcfHeader -ContentType application/json -SkipCertificateCheck
      Start-Sleep -Seconds 5
  }
  While ($null -eq $hostCommissionTaskResponse.completionTimestamp)
  Write-Debug -Message $hostCommissionTaskResponse
  if ($hostCommissionTaskResponse.status -eq "Successful")
  {
    $commissionedHosts = @()
    foreach ($hostResourceId in $hostCommissionTaskResponse.resources.resourceid) 
    {
      $commissionedHosts += Get-VcfHost -id $hostResourceId
    }
  }
  else {
      throw "There was a problem commissioning the hosts: $($hostCommissionTaskResponse.subtasks)"
  }
  Write-Progress -parentid 1 -Id 2 -Activity "Adding hosts to SDDC Manager." -Status "Commissioning complete" -PercentComplete 100
  Write-Progress -id 1 -Activity "VCF and Pure ESXi Host Commission Process" -Status "Process Complete" -PercentComplete 100
  return $commissionedHosts
}
function Get-PfaVcfVasaProvider {
    <#
    .SYNOPSIS
      Returns all VASA Providers registered in SDDC Manager.
    .DESCRIPTION
      Returns all VASA Providers registered in SDDC Manager.
    .INPUTS
      None
    .OUTPUTS
      Returns the VASA Provider(s)
    .EXAMPLE
      PS C:\ Get-PfaVcfVasaProvider
   
      Returns all VASA Providers registered in SDDC Manager.
    .NOTES
      Version: 1.0
      Author: Cody Hosterman https://codyhosterman.com
      Creation Date: 09/25/2020
      Purpose/Change: First release
   
    *******Disclaimer:******************************************************
    This scripts are offered "as is" with no warranty. While this
    scripts is tested and working in my environment, it is recommended that you test
    this script in a test lab before using in a production environment. Everyone can
    use the scripts/commands provided here without any written permission but I
    will not be liable for any damage or loss to the system.
    ************************************************************************
    #>

    try {
      Get-InstalledModule -Name PowerVCF -ErrorAction Stop |Out-Null
    }
    catch {
      throw "Please install PowerVCF with install-module PowerVCF."
    }
    if ($null -eq $global:sddcManager)
    {
      throw "Please connect to SDDC Manager with Request-VcfToken."
    }
    if ($psversiontable.PSEdition -ne "Core")
    {
      throw "The cmdlet Get-PfaVcfVasaProvider is only supported with PowerShell Core (7.x or later)."
    }
    $vcfHeader = @{authorization="Bearer $($Global:accessToken)"} 
    $vasaProviders = (Invoke-RestMethod -SkipCertificateCheck -Headers $vcfHeader -Method GET -Uri "https://$($sddcManager)/v1/vasa-providers"  -ContentType "application/json").elements
    if ($null -ne $vasaProviders)
    {
        return $vasaProviders
    }
    else {
        return $null
    }
}  
function New-PfaVcfVasaProvider {
    <#
    .SYNOPSIS
      Adds a VASA Provider to SDDC Manager.
    .DESCRIPTION
      Connects to a FlashArray pulls the correct information, and registers its CTO VASA provider with SDDC Manager.
    .INPUTS
      FlashArray IP or FQDN, user name and password.
    .OUTPUTS
      Returns the VASA Provider registration.
    .EXAMPLE
      PS C:\ New-PfaVcfVasaProvider -arrayAddress flasharray-m50-1 -username pureuser -password *********
   
      Connects to a FlashArray pulls the correct information, and registers its CTO VASA provider with SDDC Manager.
    .EXAMPLE
      PS C:\ New-PfaVcfVasaProvider -arrayAddress flasharray-m50-1 -credential (get-credential)
   
      Connects to a FlashArray pulls the correct information, and registers its CTO VASA provider with SDDC Manager.
    .NOTES
      Version: 1.0
      Author: Cody Hosterman https://codyhosterman.com
      Creation Date: 09/25/2020
      Purpose/Change: First release
   
    *******Disclaimer:******************************************************
    This scripts are offered "as is" with no warranty. While this
    scripts is tested and working in my environment, it is recommended that you test
    this script in a test lab before using in a production environment. Everyone can
    use the scripts/commands provided here without any written permission but I
    will not be liable for any damage or loss to the system.
    ************************************************************************
    #>

    [CmdletBinding(DefaultParameterSetName='Username')]
    Param(
            [Parameter(Position=0,mandatory=$True)]
            [string]$ArrayAddress,

            [Parameter(Position=1,ParameterSetName='Username',mandatory=$true)]
            [string]$Username,

            [Parameter(Position=2,mandatory=$True,ParameterSetName='Username')]
            [securestring]$Password,

            [Parameter(Position=3,ValueFromPipeline=$True,mandatory=$true,ParameterSetName='Creds')]
            [System.Management.Automation.PSCredential]$ArrayCredential,
            
            [Parameter(Position=4)]
            [ValidateSet('iSCSI','FC')]
            [string]$Protocol
    )
    try {
      Get-InstalledModule -Name PowerVCF -ErrorAction Stop |Out-Null
    }
    catch {
      throw "Please install PowerVCF with install-module PowerVCF."
    }
    if ($null -eq $global:sddcManager)
    {
      throw "Please connect to SDDC Manager with Request-VcfToken."
    }
    if ($psversiontable.PSEdition -ne "Core")
    {
      throw "The cmdlet New-PfaVcfVasaProvider is only supported with PowerShell Core (7.x or later)."
    }
    if ($null -eq $ArrayCredential)
    {
        $ArrayCredential = New-Object System.Management.Automation.PSCredential ($Username, $Password)
    }
    $fa = New-PfaArray -EndPoint $ArrayAddress -Credentials $ArrayCredential -IgnoreCertificateError
    $mgmtIP = New-PfaRestOperation -resourceType network -restOperationType GET -flasharray $fa -SkipCertificateCheck |Where-Object {$_.name -like "CT0.eth0"}
    $arrayname = New-PfaRestOperation -resourceType array -restOperationType GET -flasharray $fa -SkipCertificateCheck
    if ([string]::IsNullOrWhiteSpace($Protocol))
    {
      $foundProtocol = checkFaProtocol -flasharray $fa -ErrorAction stop
    }
    else {
      $foundProtocol = checkFaProtocol -flasharray $fa -protocol $Protocol -ErrorAction stop
    }
    $FaName = ("$($arrayname.array_name)-CT0") 
    $VasaUrl = ("https://$($mgmtIP.address):8084/version.xml") 
    $stdPassword = ConvertFrom-SecureString $ArrayCredential.password -AsPlainText
    $vasaBody = "{
        `"name`": `"$($FaName)`",
        `"storageContainers`": [ {
            `"name`": `"Vvol container`",
            `"protocolType`": `"$($foundProtocol)`"
        } ],
        `"url`": `"$($VasaUrl)`",
        `"users`": [ {
            `"password`": `"$($stdPassword)`",
            `"username`": `"$($ArrayCredential.UserName)`"
        } ]
    }"

    Write-Debug $vasaBody
    $vcfHeader = @{authorization="Bearer $($Global:accessToken)"} 
    $vasaProvider = Invoke-RestMethod -SkipCertificateCheck -Headers $vcfHeader -Method POST -Uri "https://$($sddcManager)/v1/vasa-providers" -Body $vasaBody -ContentType "application/json"
    return $vasaProvider
}  
function checkDefaultFlashArray{
    if ($null -eq $Global:DefaultFlashArray)
    {
        throw "You must pass in a FlashArray connection or create a default FlashArray connection with New-Pfaconnection"
    }
    else 
    {
        return $Global:DefaultFlashArray
    }
}
function checkFaProtocol{
  [CmdletBinding()]
    Param(
        [Parameter(Position=0,mandatory=$true)]
        [PurePowerShell.PureArray]$Flasharray,

        [Parameter(Position=1)]
        [string]$Protocol
    )
    $arrayname = New-PfaRestOperation -resourceType array -restOperationType GET -flasharray $Flasharray -SkipCertificateCheck
    $arrayPorts = New-PfaRestOperation -resourceType port -restOperationType GET -flasharray $Flasharray -SkipCertificateCheck
    $iscsi = $false
    $fc = $false
    
    if (($arrayPorts |where-object {$null -ne $_.iqn}).count -ne 0)
    {
        $iscsi = $true
    }
    if (($arrayPorts |where-object {$null -ne $_.wwn}).count -ne 0)
    {
        $fc = $true
    }
    if (($iscsi -eq $true) -and ($fc -eq $false))
    {
        $FoundProtocol = "iSCSI"
    }
    if (($iscsi -eq $false) -and ($fc -eq $True))
    {
        $FoundProtocol = "FC"
    }
    if (($iscsi -eq $false) -and ($fc -eq $false))
    {
        throw "Neither Fibre Channel or iSCSI ports were found on the input array $($arrayname.array_name)"
    }
    if (($iscsi -eq $true) -and ($fc -eq $true))
    {
        if ([string]::IsNullOrWhiteSpace($Protocol))
        {
            throw "Both Fibre Channel and iSCSI found on this array. Please specify the desired protocol in the -protocol parameter (iSCSI or FC)"
        }
        $FoundProtocol = $Protocol
    }
    if (![string]::IsNullOrWhiteSpace($Protocol))
    {
        if ($Protocol -ne $FoundProtocol)
        {
            throw "Specified protocol $($protocol) is not found on the array. Only $($foundProtocol) is found on $($arrayname.array_name)"
        }
    }
    return $FoundProtocol
}