Puneet Tiwari
Puneet Tiwari

Reputation: 41

how to use variable out of invoke-command in powershell?

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```

Upvotes: 0

Views: 167

Answers (1)

Dilly B
Dilly B

Reputation: 1462

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"

Upvotes: 1

Related Questions