0

I have below Invoke-command code, the script using hponcfg.exe file on remote server to get ILO configuration. few servers having issue with power capping and error returned by hponcfg.exe as "Message = 0x0089 Power capping information is not available at this time, try again later."

My question is: I want to capture this error if generated by hponcfg inside invoke-command scriptblock and use it out of scriptblock.

$CurrentDir = (Split-Path $invocation.MyCommand.Path).ToLower()
$CurrentDir
$Credential = get-credential -message "Please supply SA account details."
$servers = gc .\servers.txt
#$Global:ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$date = (get-date).ToString("yyyyMMdd_HHmm")
$ILOContent = ".\ILOConfigData_$date.csv"
New-Item -path $ILOContent -type file -Force | out-null
Add-Content -Path $ILOContent -Value "ILO_Name,Model,ILOFIrmware,ILODevice,ILOFWDate,ILO_Domain,Network_Details,ILO_TimeZone,Directory_Users,LDAP_Directory_Authentication,Directory_Groups,SNMP_Settings,Directory_Server_Address"



Foreach($server in $servers){

    if (Test-Connection -ComputerName $server -Quiet)
        {
                    #$Frompath = ".\ILO_Prerequisite\"
                    #$To_Path = "C:\Program Files\Hewlett Packard Enterprise\HPONCFG"
                    $tmp="Drv_$server"
                    new-psdrive $tmp filesystem "\\$server\C$" -cred $cred|Out-Null
                    $Model = (Get-WmiObject -ComputerName $server -Class:Win32_ComputerSystem).model
                    
                    Write-Host "Validating HPE pre-requisites on server:"$server -BackgroundColor DarkGray -ForegroundColor White
                    if (-not(test-path("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG")))
                    {  
                        Write-Host "Corrupt 'HPONCFG' folder structure found. Remediating, will take few seconds." -ForegroundColor Red
                        New-Item -Path ("$($tmp):\Program Files\Hewlett Packard Enterprise\") -ItemType Directory -Name HPONCFG -Force|Out-Null
                        
                        $To_Path =("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG")
                        $From_Path = ".\ILO-PreRequisite\*"
                        copy-item -path $From_Path -Destination $To_Path -recurse -Force
                        Sleep(6)
                        Write-Host "'HPONCFG' folder structure remediated." -ForegroundColor Green
                    }
                    Elseif (-not(test-path("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe")))
                            {
                                $To_Path =("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG")
                                Write-Host "Corrupt 'HPONCFG' folder structure found. Remediating, will take few seconds." -ForegroundColor Red
                                copy-item -path $From_Path -Destination $To_Path -recurse -Force
                                Sleep(6)
                                Write-Host "'HPONCFG' folder structure remediated" -ForegroundColor Green
                            }
                          remove-psdrive -name $tmp -force


                    #if (-not(test-path "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe"))
                   # {
                        # do copy job
                    #    write-host "Copying files and folders from $frompath to $topath"  -ForegroundColor Yellow
                    #    copy-item -path $frompath -Destination $topath -recurse
                   # }

            $export = Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
                   
                    New-Item -Path "C:\Program Files\Hewlett Packard Enterprise\HPONCFG" -ItemType File -Name Current_ILOConfig.xml -Force| Out-Null
                    Set-Location "C:\Program Files\Hewlett Packard Enterprise\HPONCFG"
                    $ILODataPath = Get-Location
                    $WantFile = "$ILODataPath\Current_ILOConfig.txt"
                    $FileExists = Test-Path $WantFile
                    If ($FileExists -eq $True) {Remove-Item $WantFile }
                    Sleep(2)
                    Write-Host "Gathering current ILO configuration for $ENV:COMPUTERNAME"  -ForegroundColor Yellow
                    & "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w `
                      "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" |Out-Null
                    
                    Get-Content .\Current_ILOConfig.xml
                    }
            $export|Out-File "Current_ILOConfig.txt"
        
            Sleep(3)
            $ILORAW_DATA = Get-Content .\Current_ILOConfig.txt

            $ILORAW_DATA|ForEach-Object{
                    $_ -replace '<!-- ' `
                    -replace ' -->' `
                    -replace '<' `
                    -replace ' />' `
                    -replace '"' `
                    }|Set-Content .\Current_ILOConfig.txt

            $ILO_DATA = Get-Content .\Current_ILOConfig.txt
            
            Write-Host "Getting ILO DNS details"
            $DNS_NAME = $ILO_DATA |Where {$_ |Select-String -Pattern " DNS_NAME VALUE"," DOMAIN_NAME VALUE"}
            $ILONAME = $DNS_NAME -split "="
            $ILO_Name = $ILONAME[1]
            $ILO_Domain = $ILONAME[3]

            Write-Host "Getting ILO Network details"
            $NT = $ILO_DATA | where {$_ |Select-String -Pattern " IP_ADDRESS VALUE"," SUBNET_MASK"," GATEWAY_IP_ADDRESS"," PRIM_DNS_SERVER VALUE", " SEC_DNS_SERVER VALUE"," TER_DNS_SERVER VALUE" } 
            $Network = [array]$NT -join "`n"
            $Network_Details = $Network.Trim()

            Write-Host "Getting ILO TimeZone"
            $TZ= $ILO_DATA |Where {$_ | Select-String -Pattern " TIMEZONE VALUE"}
            $TimeZone =$TZ -Split "="
            $ILO_TimeZone = $TimeZone[1]

            Write-Host "Getting ILO Directory Server Address" # Directory_Server_Address
            $DSA = $ILO_DATA |Where {$_ | Select-String -Pattern " DIR_SERVER_ADDRESS"}
            $DIR_SERVERADDRESS = $DSA -Split "="
            $Directory_Server_Address = $DIR_SERVERADDRESS[1]

            $ILODeviceID = @()
            $ILODev = $ILO_DATA|where{$_|Select-String -Pattern "Device: "}
            $ILODevStr = $ILODev -split(' ')
            $ILODeviceID += $ILODevStr[1..2] -as [string]
            $ILODeviceID += $ILODevStr[7]
            $ILODeviceID += $ILODevStr[-1]

            Write-Host "Getting LDAP Directory Authentication Enabled/Disabled?"
            $LDAP_DIR = $ILO_DATA |Where {$_ | Select-String -Pattern " DIR_AUTHENTICATION_ENABLED"}
            $LDAP_DIR_STATUS = $LDAP_DIR -split "="
            $LDAP_Directory_Authentication = $LDAP_DIR_STATUS[1]
      
            Write-Host "Getting ILO Device detail"
            $ILOFIrmware = $ILODevStr[7]
            Write-Host "Getting ILO Firmware Version"
            $ILODevice   = $ILODevStr[1,2]
            Write-Host "Getting ILO Firmware Version date"
            $ILOFWDate   = $ILODevStr[-1]

            Write-Host "Getting SNMP Settings" #SNMP_Settings
            $SNMPADDRESS = $ILO_DATA |Where {$_ | Select-String -Pattern "SNMP_ADDRESS"}
            $SNMP_DATA = @()

                foreach($SNMP in $SNMPADDRESS)
                {
                 $SNMP_DATA +=($SNMP -split "VALUE=")[1]
                }
                $SNMP_Settings = $SNMP_DATA -join "`n"

            
            Write-Host "Getting ILO Directory User details"
        
            $DIR_USER = $ILO_DATA |Where {$_ | Select-String -Pattern " DIR_USER_CONTEXT"}
            $User =@()
        
                foreach($Usr in $DIR_USER)
                {
                 $User += ($Usr -split "VALUE=")[1]
              
                }
                 #$User
                 $Directory_Users = $User -join "`n"

            #group Account details
            Write-Host "Getting ILO Directory Group details"
            $DIR_GRPACCT = $ILO_DATA |Where {$_ | Select-String -pattern " DIR_GRPACCT"}

            $ACCTs = @()
            for($a=1;$a -le 10;$a++)
            {
                $GroupName = "DIR_GRPACCT" + $a + "_NAME"
                #$Privilege = "DIR_GRPACCT" + $a + "_PRIV"
                $DIR_GRPACCT = $ILO_DATA |Where {$_ | Select-String -pattern $groupname}
                
                foreach ($acct in $DIR_GRPACCT)
                {

                    $ACCTS += ($acct -split "VALUE=")[1]
                }
                $DIR_GRPACCTS = ($ACCTS -join "`n")
                
            }
                            
            $data = "`"$ILO_Name`",`"$Model`",`"$ILOFIrmware`",`"$ILODevice`",`"$ILOFWDate`",`"$ILO_Domain`",`"$Network_Details`",`"$ILO_TimeZone`",`"$($Directory_Users.trimend())`",`"$LDAP_Directory_Authentication`",`"$($DIR_GRPACCTS.trimend())`",`"$($SNMP_Settings.trimend())`",`"$($Directory_Server_Address.trimend())`""
            $Data |Out-File -Append $ILOContent
        }
        else
        {
            write-host -ForegroundColor Red "Server $server is not reachable"
            $data = "`"$server`",`"not reachable`""
            
            $Data |Out-File -Append $ILOContent
        } 
 }    
 
 #Clear User defined variables
 Write-Host "Performing Clean-up" -ForegroundColor Yellow
 
 #Clear-Variable -Name ILO*      
 Function Get-ScriptVariable ($Name = '*')
{
  # these variables may exist in certain environments (like ISE, or after use of foreach)
  $special = 'ps','psise','psunsupportedconsoleapplications', 'foreach', 'profile'

  $ps = [PowerShell]::Create()
  $null = $ps.AddScript('$null=$host;Get-Variable') 
  $reserved = $ps.Invoke() | 
    Select-Object -ExpandProperty Name
  $ps.Runspace.Close()
  $ps.Dispose()
  Get-Variable -Scope Global | 
    Where-Object Name -like $Name |
    Where-Object { $reserved -notcontains $_.Name } |
    Where-Object { $special -notcontains $_.Name } |
    Where-Object Name 
}Get-ScriptVariable|Out-Null
 Get-ScriptVariable |Clear-Variable ;Write-Host "Clean-up completed." -ForegroundColor Green

  Write-Host "Check detailed log stored at path: "$CurrentDir -ForegroundColor Green```
1
  • The code you added is not a minimal reproducible example, and IMO it adds confusion to the question. Please trim this down to a minimum example. Commented Nov 2, 2021 at 6:29

1 Answer 1

1

You can use try-catch-finally method to get your error messages. Hi I have modified your script invoke-command part only. Please test and use it. This script is not tested.

$export = Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
            try {    
                New-Item -Path "C:\Program Files\Hewlett Packard Enterprise\HPONCFG" -ItemType File -Name Current_ILOConfig.xml -Force | Out-Null
                Set-Location "C:\Program Files\Hewlett Packard Enterprise\HPONCFG"
                $ILODataPath = Get-Location
                $WantFile = "$ILODataPath\Current_ILOConfig.txt"
                $FileExists = Test-Path $WantFile
                If ($FileExists -eq $True) { Remove-Item $WantFile }
                Sleep(2)
                Write-Host "Gathering current ILO configuration for $ENV:COMPUTERNAME"  -ForegroundColor Yellow
                & "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w `
                    "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" | Out-Null
                Get-Content .\Current_ILOConfig.xml
            }
            catch {
                return $_     
            }  
                    
        }
$export | Out-File "Current_ILOConfig.txt"
Sign up to request clarification or add additional context in comments.

6 Comments

I am new to powershell and not much familiar with try-catch-finally. now sure how to implement it in the script. I have updated my code with my working script. please suggest
@PuneetTiwari I fixed the code sample so the use of try/catch should be clear now. Previously, a few of the lines were not formatted as a block of code.
@Bender: Try-Catch only to be inside Scriptblock in script posted above?
If the code inside the try block throws a terminating error the code in the catch block will run instead of halting execution. You can put all of your code inside the try, or you can place the try /catch only around the code which needs it.
``` & "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w ` "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" | Out-Null ``` throws error 0x0089. How can error "Message = Power capping information is not available at this time, try again later" be captured which is returned by this exe in a variable and use it outside scriptblock? Error: if any server having power capping issue <!-- Status = 0x0089--> <!-- Message = Power capping information is not available at this time, try again later.-->
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.