Home > Storage > Data Storage Essentials > Storage Admin > The Next Generation PowerMax - Balancing Performance with Efficiency and Sustainability > Appendix
This section provides a more detailed explanation of each significant step in the provided Redfish iPDU PowerShell script. Overall, the script prompts the user for an iPDU's IP address, validates it, handles authentication, and retrieves power data using the obtained authentication token. It incorporates error handling and displays appropriate messages throughout the process.
# Enter IP Address of iPDU
$isValidIpAddress = $false
do {
$ipAddress = Read-Host -Prompt “Enter the iPDU’s IP address”
$ip = $null
if ([System.Net.IPAddress]::TryParse($ipAddress, [ref]$ip)) {
$isValidIpAddress = $true
} else {
Write-Host “The entered IP address is not valid. Please enter a different IP address.”
}
} until ($isValidIpAddress)
The script uses a `do-while` loop to repeatedly prompt the user to enter the IP address until a valid IP address is provided.
The `Read-Host` cmdlet captures the input from the user.
The `[System.Net.IPAddress]::TryParse($ipAddress, [ref]$ip)` method attempts to parse the IP address string. If successful, it assigns the parsed IP address to the `$ip` variable and returns `$true`, indicating a valid IP address.
If the IP address is not valid, the script displays an error message and prompts the user to enter a different IP address.
Using this method of having the user manually enter the IP address of the iPDU allows for easier re-usability of the script for different environments, rather than hard coding the IP address into the script in plain text
$url = “https://$ipAddress/redfish/v1/SessionService/Sessions”
$powerUrl = “https://$ipAddress/redfish/v1/PowerEquipment/RackPDUs/1/Sensors/PDUPower”
The script constructs the URLs for the session service and power data based on the entered IP address.
Creating a session to handle authentication
# Create a session to handle the authentication
$session = [System.Net.HttpWebRequest]::Create($url)
$session.Method = “POST”
$session.ContentType = “application/json”
# Set the timeout for the session request
$session.Timeout = 120000 # 120 seconds (change as required)
The script creates an HTTP session for authentication using the `$url` as the endpoint.
It sets the request method to POST and the content type to JSON.
The timeout is set to 120 seconds.
Prompting for username and password
$credentials = Get-Credential -Message “Enter your credentials”
The `Get-Credential` cmdlet prompts the user to enter their username and password.
Using the get-credential cmdlet is much more secure than hard coding username and password information in clear text within the script. Get-Credential securely stores the entered username password as a secure string, providing an additional layer of protection.
This cmdlet allows for easier re-usability of the script across different iPDU environments.
Sending a POST request to authenticate and obtain the authentication token:
# Send a POST request to authenticate and obtain the authentication token
$payload = @{
UserName = $credentials.UserName
Password = $credentials.GetNetworkCredential().Password
} | ConvertTo-Json
$payloadBytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
$session.ContentLength = $payloadBytes.Length
$stream = $session.GetRequestStream()
$stream.Write($payloadBytes, 0, $payloadBytes.Length)
$stream.Close()
$response = $session.GetResponse()
$authenticationToken = $response.Headers[“X-Auth-Token”]
The portion of the script creates a payload containing the username and password entered by the user.
The payload is converted to JSON format.
The script writes the payload to the request stream and sends a POST request to authenticate and obtain the authentication token.
The response is captured, and the authentication token is extracted from the response headers.
**Checking if authentication was successful:**
if ($response.StatusCode -eq 201) {
Write-Host "Authentication successful. Authentication Token: $authenticationToken"
The script checks the status code of the response to determine if the authentication was successful (status code 201) or not
Using the authentication token for subsequent requests:
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$($credentials.UserName):$authenticationToken"))
# Use the authentication token for subsequent requests
$powerRequest = [System.Net.HttpWebRequest]::Create($powerUrl)
$powerRequest.Method = "GET"
$powerRequest.Headers.Add("X-Auth-Token", $authenticationToken)
$powerRequest.Headers.Add("Authorization", "Basic $encodedCredentials")
# Set the timeout for the power request
$powerRequest.Timeout = 300000 # 300 seconds (increase the timeout as needed)
The script encodes the credentials and authentication token in Base64 format to create the encoded credentials.
It creates a new HTTP request for retrieving power data using the `$powerUrl` as the endpoint.
The authentication token is added to the request headers using the "X-Auth-Token" key, and the encoded credentials are added using the "Authorization" key.
The timeout for the power request is set to 300 seconds.
Handling the power request and processing the response
try {
$powerResponse = $powerRequest.GetResponse()
# Check if the power request was successful
if ($powerResponse.StatusCode -eq 200) {
$powerStream = $powerResponse.GetResponseStream()
if ($powerStream.CanRead) {
$powerReader = [System.IO.StreamReader]::new($powerStream)
$powerData = $powerReader.ReadToEnd()
$powerReader.Close()
$powerStream.Close()
# Process the power response data as needed
Write-Host "Power data received:"
Write-Host $powerData
} else {
Write-Host "Power stream is not readable."
}
} else {
Write-Host "Failed to retrieve power data. Status code: $($powerResponse.StatusCode)"
}
# Close the power response
$powerResponse.Close()
} catch {
Write-Host "An error occurred: $_"
}
} else {
Write-Host "Authentication failed. Status code: $($response.StatusCode)"
}
This section is the heart of the script as it does the following key actions:
If the power request's status code is not 200, it outputs a message indicating that the retrieval of power data failed, along with the actual status code.
The code is enclosed in a try block. This allows for the execution of a block of code while providing error handling if an exception occurs.
Within the try block, a request is made using the $powerRequest object. The GetResponse() method is called on $powerRequest, which retrieves a response from the iPDU.
The code then checks if the power request was successful by examining the StatusCode property of the $powerResponse object. If the status code is 200 (indicating a successful request), the code proceeds to process the response data.
If the power stream ($powerStream) is readable, it creates a StreamReader object ($powerReader) to read the response stream. The ReadToEnd() method is called on $powerReader to read the entire response data into the $powerData variable. The $powerReader and $powerStream objects are then closed.
The code then proceeds to process the $powerData as needed and outputs the received power data using the Write-Host cmdlet.
If the power stream is not readable, it outputs a message indicating that the stream is not readable.
After processing the power response, the $powerResponse object is closed using the Close() method
If an exception occurs within the try block, the catch block is executed. It outputs an error message indicating the exception that occurred.
If the initial authentication for the request failed, the else block is executed. It outputs a message indicating the authentication failure, along with the corresponding status code.
Closing the session response:
# Close the session response
$response.Close()