Set-NextOneTimeBootVirtualMediaDeviceOemREDFISH.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
<#
_author_ = Texas Roemer <Texas_Roemer@Dell.com>
_version_ = 4.0
 
Copyright (c) 2020, Dell, Inc.
 
This software is licensed to you under the GNU General Public License,
version 2 (GPLv2). There is NO WARRANTY for this software, express or
implied, including the implied warranties of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
along with this software; if not, see
http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
#>


<#
.Synopsis
  Cmdlet using Redfish API with OEM extension to set next onetime boot device to either virtual optical or virtual floppy.
.DESCRIPTION
   Cmdlet using Redfish API with OEM extension to set next onetime boot device to either virtual optical or virtual floppy. DMTF doesn't support setting virtual CD or virtual floppy as next one time boot. This cmdlet uses OEM extension to solve this issue.
   - idrac_ip: Pass in iDRAC IP address, REQUIRED
   - idrac_username: Pass in iDRAC username, REQUIRED
   - idrac_password: Pass in iDRAC username password, REQUIRED
   - next_onetime_boot_device: Set next onetime boot device. Pass in '1' for virtual CD or '2' for virtual floppy
   - reboot_server: Pass in 'y' to reboot the server now to boot to onetime boot device or 'n' to not reboot the server. Passing in 'n' will still set next onetime boot device which will happen on next server manual reboot.
    
    
 
.EXAMPLE
   Set-NextOneTimeBootVirtualMediaDeviceOemREDFISH -idrac_ip 192.168.0.120 -idrac_username root -idrac_password calvin -next_onetime_boot_device 1 -reboot_server y
   This example will set next onetime boot device to virtual CD and reboot the server now
.EXAMPLE
   Set-NextOneTimeBootVirtualMediaDeviceOemREDFISH -idrac_ip 192.168.0.120 -idrac_username root -idrac_password calvin -next_onetime_boot_device 2 -reboot_server n
   This example will set next onetime boot device to virtual floppy and not reboot the server. Set onetime boot device is still set and will boot to this device on next manual reboot.
#>


function Set-NextOneTimeBootVirtualMediaDeviceOemREDFISH {



param(
    [Parameter(Mandatory=$True)]
    $idrac_ip,
    [Parameter(Mandatory=$True)]
    $idrac_username,
    [Parameter(Mandatory=$True)]
    $idrac_password,
    [Parameter(Mandatory=$True)]
    [string]$next_onetime_boot_device,
    [Parameter(Mandatory=$True)]
    [string]$reboot_server
    )


# Function to igonre SSL certs

function Ignore-SSLCertificates
{
    $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
    $Compiler = $Provider.CreateCompiler()
    $Params = New-Object System.CodeDom.Compiler.CompilerParameters
    $Params.GenerateExecutable = $false
    $Params.GenerateInMemory = $true
    $Params.IncludeDebugInformation = $false
    $Params.ReferencedAssemblies.Add("System.DLL") > $null
    $TASource=@'
        namespace Local.ToolkitExtensions.Net.CertificatePolicy
        {
            public class TrustAll : System.Net.ICertificatePolicy
            {
                public bool CheckValidationResult(System.Net.ServicePoint sp,System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem)
                {
                    return true;
                }
            }
        }
'@
 
    $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
    $TAAssembly=$TAResults.CompiledAssembly
    $TrustAll = $TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy = $TrustAll
}

# Function to get Powershell version

function get_powershell_version 
{
$get_host_info = Get-Host
$major_number = $get_host_info.Version.Major
$global:get_powershell_version = $major_number
}

get_powershell_version

# Function to set up iDRAC credentials

function setup_idrac_creds
{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::TLS12
$user = $idrac_username
$pass= $idrac_password
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$global:credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
}

# function to reboot server

function reboot_server
{
$uri = "https://$idrac_ip/redfish/v1/Systems/System.Embedded.1/"
    try
    {
    if ($global:get_powershell_version -gt 5)
    {
    $result = Invoke-WebRequest -SkipCertificateCheck -SkipHeaderValidation -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    else
    {
    Ignore-SSLCertificates
    $result = Invoke-WebRequest -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    }
    catch
    {
    Write-Host
    $RespErr
    return
    }

    if ($result.StatusCode -eq 200)
    {
    Write-Host
    [String]::Format("- PASS, statuscode {0} returned successfully to get current power state",$result.StatusCode)
    }
    else
    {
    [String]::Format("- FAIL, statuscode {0} returned",$result.StatusCode)
    break
    }

$result_output = $result.Content | ConvertFrom-Json
$power_state = $result_output.PowerState

    if ($power_state -eq "On")
    {
    Write-Host "- WARNING, Server current power state is ON, performing graceful shutdown"
    $JsonBody = @{ "ResetType" = "GracefulShutdown"} | ConvertTo-Json -Compress
    $uri = "https://$idrac_ip/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
    try
    {
    if ($global:get_powershell_version -gt 5)
    {
    
    $result1 = Invoke-WebRequest -UseBasicParsing -SkipHeaderValidation -SkipCertificateCheck -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    else
    {
    Ignore-SSLCertificates
    $result1 = Invoke-WebRequest -UseBasicParsing -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    }
    catch
    {
    Write-Host
    $RespErr
    return
    } 

    if ($result1.StatusCode -eq 204)
    {
    [String]::Format("- PASS, statuscode {0} returned to attempt graceful server shutdown",$result1.StatusCode)
    Start-Sleep 15
    }
    else
    {
    [String]::Format("- FAIL, statuscode {0} returned",$result1.StatusCode)
    break
    }

        $count = 1
        while($true)
        {
        $uri = "https://$idrac_ip/redfish/v1/Systems/System.Embedded.1/"
        try
    {
    if ($global:get_powershell_version -gt 5)
    {
    $result = Invoke-WebRequest -SkipCertificateCheck -SkipHeaderValidation -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    else
    {
    Ignore-SSLCertificates
    $result = Invoke-WebRequest -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    }
    catch
    {
    Write-Host
    $RespErr
    return
    }
        $result_output = $result.Content | ConvertFrom-Json
        $power_state = $result_output.PowerState

        if ($power_state -eq "Off")
        {
        Write-Host "- PASS, validated server in OFF state"
        break
        }
        elseif ($count -eq 5)
        {
        Write-Host "- WARNING, server did not accept graceful shutdown request, performing force off"
        $JsonBody = @{ "ResetType" = "ForceOff"} | ConvertTo-Json -Compress
        $uri = "https://$idrac_ip/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
        try
    {
    if ($global:get_powershell_version -gt 5)
    {
    
    $result1 = Invoke-WebRequest -UseBasicParsing -SkipHeaderValidation -SkipCertificateCheck -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    else
    {
    Ignore-SSLCertificates
    $result1 = Invoke-WebRequest -UseBasicParsing -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    }
    catch
    {
    Write-Host
    $RespErr
    return
    } 

        if ($result1.StatusCode -eq 204)
        {
        [String]::Format("- PASS, statuscode {0} returned to force power OFF the server",$result1.StatusCode)
        Start-Sleep 15
        }
        else
        {
        [String]::Format("- FAIL, statuscode {0} returned",$result1.StatusCode)
        break
        }
        }
        else
        {
        Write-Host "- WARNING, server still in ON state waiting for graceful shutdown to complete, will check server status again in 1 minute"
        $count++
        Start-Sleep 60
        continue
        }
        }

    $JsonBody = @{ "ResetType" = "On"
    } | ConvertTo-Json -Compress
    $uri = "https://$idrac_ip/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
    try
    {
    if ($global:get_powershell_version -gt 5)
    {
    
    $result1 = Invoke-WebRequest -UseBasicParsing -SkipHeaderValidation -SkipCertificateCheck -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    else
    {
    Ignore-SSLCertificates
    $result1 = Invoke-WebRequest -UseBasicParsing -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    }
    catch
    {
    Write-Host
    $RespErr
    return
    } 

    if ($result1.StatusCode -eq 204)
    {
    [String]::Format("- PASS, statuscode {0} returned successfully to power ON the server",$result1.StatusCode)
    $power_state = "On"
    }
    else
    {
    [String]::Format("- FAIL, statuscode {0} returned",$result1.StatusCode)
    break
    }
    }


if ($power_state -eq "Off")
{
Write-Host "- WARNING, server in OFF state, powering ON server"
$JsonBody = @{ "ResetType" = "On"} | ConvertTo-Json -Compress
$uri = "https://$idrac_ip/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"

# POST command to power ON the server
try
    {
    if ($global:get_powershell_version -gt 5)
    {
    
    $result1 = Invoke-WebRequest -UseBasicParsing -SkipHeaderValidation -SkipCertificateCheck -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    else
    {
    Ignore-SSLCertificates
    $result1 = Invoke-WebRequest -UseBasicParsing -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    }
    catch
    {
    Write-Host
    $RespErr
    return
    } 

if ($result1.StatusCode -eq 204)
{
    [String]::Format("- PASS, statuscode {0} returned successfully to power ON the server",$result1.StatusCode)
}
else
{
    [String]::Format("- FAIL, statuscode {0} returned",$result1.StatusCode)
    break
}
}
}

# Function to set next onetime boot device

function set_next_onetime_boot_OEM 
{

    if ($next_onetime_boot_device -eq "1")
    {
    Write-Host "`n- WARNING, setting next one time boot device to Virtual CD"
    $JsonBody = @{"ShareParameters"=@{"Target"="ALL"};"ImportBuffer"="<SystemConfiguration><Component FQDD='iDRAC.Embedded.1'><Attribute Name='ServerBoot.1#BootOnce'>Enabled</Attribute><Attribute Name='ServerBoot.1#FirstBootDevice'>VCD-DVD</Attribute></Component></SystemConfiguration>"} | ConvertTo-Json -Compress
    }
    elseif ($next_onetime_boot_device -eq "2")
    {
    Write-Host "`n- WARNING, setting next one time boot device to Virtual Floppy"
    $JsonBody = @{"ShareParameters"=@{"Target"="ALL"};"ImportBuffer"="<SystemConfiguration><Component FQDD='iDRAC.Embedded.1'><Attribute Name='ServerBoot.1#BootOnce'>Enabled</Attribute><Attribute Name='ServerBoot.1#FirstBootDevice'>vFDD</Attribute></Component></SystemConfiguration>"} | ConvertTo-Json -Compress
    }
    else
    {
    Write-Host "- FAIL, invalid value passed in for 'next_onetime_boot_device' parameter"
    return
    }


$uri = "https://$idrac_ip/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/EID_674_Manager.ImportSystemConfiguration"

# POST command to import or export server configuration profile file

    try
    {
    if ($global:get_powershell_version -gt 5)
    {
    
    $post_result = Invoke-WebRequest -UseBasicParsing -SkipHeaderValidation -SkipCertificateCheck -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    else
    {
    Ignore-SSLCertificates
    $post_result = Invoke-WebRequest -UseBasicParsing -Uri $uri -Credential $credential -Method Post -ContentType 'application/json' -Headers @{"Accept"="application/json"} -Body $JsonBody -ErrorVariable RespErr
    }
    }
    catch
    {
    Write-Host
    $RespErr
    return
    } 
$raw_content=$post_result.RawContent | ConvertTo-Json
$find_jobID=[regex]::Match($raw_content, "JID_.+?r").captures.groups[0].value
$job_id=$find_jobID.Replace("\r","")

    if ($post_result.StatusCode -eq 202)
    {
    Write-Host
    [String]::Format("- PASS, statuscode {0} returned to successfully create Server Configuration Profile(SCP) import job: {1}",$post_result.StatusCode,$job_id)
    Write-Host
    }
    else
    {
    [String]::Format("- FAIL, statuscode {0} returned",$post_result.StatusCode)
    return
    }

$get_time_old=Get-Date -DisplayHint Time
$start_time = Get-Date
$end_time = $start_time.AddMinutes(30)

while ($true)
{
$loop_time = Get-Date
$uri ="https://$idrac_ip/redfish/v1/Managers/iDRAC.Embedded.1/Jobs/$job_id"
try
    {
    if ($global:get_powershell_version -gt 5)
    {
    $get_result = Invoke-WebRequest -SkipCertificateCheck -SkipHeaderValidation -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    else
    {
    Ignore-SSLCertificates
    $get_result = Invoke-WebRequest -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    }
    catch
    {
    Write-Host "`n- WARNING, iDRAC version detected does not support this feature using Redfish API or incorrect iDRAC user credentials passed in.`n"
    $RespErr
    return
    }

$overall_job_output=$get_result.Content | ConvertFrom-Json

if ($overall_job_output.Message -eq "Successfully imported and applied Server Configuration Profile.")
{
Write-Host "- PASS, job ID '$job_id' successfully marked completed to set next onetime boot device"
    if ($reboot_server.ToLower() -eq "y")
    {
    Write-Host "- WARNING, user selected to automaticaly reboot the server now to boot to onetime boot device"
    reboot_server
    }
    elseif ($reboot_server.ToLower() -eq "n")
    {
    Write-Host "- WARNING, user selected to not automatically reboot the server. Onetime boot device is still set and will boot to this device on next manual reboot"
    }
    return
    }

elseif ($overall_job_output.Message.Contains("Fail") -or $overall_job_output.Message.Contains("fail") -or $overall_job_output.Message.Contains("Unable") -or $overall_job_output.Message.Contains("unable")) 
{
Write-Host
[String]::Format("- FAIL, final job status is: {0}",$overall_job_status.JobState)
Return
}

elseif ($loop_time -gt $end_time)
{
Write-Host "- FAIL, timeout of 30 minutes has been reached before marking the job completed"
return
}

elseif ($overall_job_output.Message -eq "Import of Server Configuration Profile operation completed with errors." -or $overall_job_output.Message -eq "Unable to complete application of configuration profile values.") 
{
$uri ="https://$idrac_ip/redfish/v1/TaskService/Tasks/$job_id"

try
    {
    if ($global:get_powershell_version -gt 5)
    {
    $result = Invoke-WebRequest -SkipCertificateCheck -SkipHeaderValidation -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    else
    {
    Ignore-SSLCertificates
    $result = Invoke-WebRequest -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    }
    catch
    {
    Write-Host "`n- WARNING, iDRAC version detected does not support this feature using Redfish API or incorrect iDRAC user credentials passed in.`n"
    $RespErr
    return
    }


Write-Host "- WARNING, failure detected for import job id '$job_id'. Check 'Messages' property below for more information on the failure."
$result.Content | ConvertFrom-Json
return
}

elseif ($overall_job_output.Message -eq "No changes were applied since the current component configuration matched the requested configuration.")
{
Write-Host "- WARNING, import job id '$job_id' completed. No changes were applied since the current component configuration matched the requested configuration. Check iDRAC settings to see if next onetime boot device is already set."
return
}


Write-Host "- Job ID '$job_id' not marked completed, checking job status again"
Start-Sleep 1
}

}

# run code

get_powershell_version
setup_idrac_creds

# Check to validate iDRAC version detected supports this feature

$uri = "https://$idrac_ip/redfish/v1/Managers/iDRAC.Embedded.1"
try
    {
    if ($global:get_powershell_version -gt 5)
    {
    $result = Invoke-WebRequest -SkipCertificateCheck -SkipHeaderValidation -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    else
    {
    Ignore-SSLCertificates
    $result = Invoke-WebRequest -Uri $uri -Credential $credential -Method Get -UseBasicParsing -ErrorVariable RespErr -Headers @{"Accept"="application/json"}
    }
    }
    catch
    {
    Write-Host "`n- WARNING, iDRAC version detected does not support this feature using Redfish API or incorrect iDRAC user credentials passed in.`n"
    $RespErr
    return
    }

if ($get_result.StatusCode -eq 200 -or $result.StatusCode -eq 202)
{
$get_actions = $get_result.Content | ConvertFrom-Json
$scp_import_action = "OemManager.v1_0_0#OemManager.ImportSystemConfiguration"
try
{
$test = $get_actions.Actions.Oem.$scp_import_action.target.GetType()
}
catch
{
Write-Host "`n- WARNING, iDRAC version detected does not support this feature using Redfish API or incorrect iDRAC user credentials passed in.`n"
return
}
}


set_next_onetime_boot_OEM 

}