简体   繁体   中英

pick required content from text file located on multiple remote servers and write to log in csv from where script is executed

I am writing a script to read a text file from multiple remote servers and get required details from text file writing those details to csv log file creating on pc from where script is executed. I want to add try, catch and if condition to get my script working as expected. Requirement as below:

  1. read file from remote server located under path,
  2. replace unwanted characters ( which is being done by code -replace)
  3. saving text file with set-content(already done)
  4. get required content from file, store in a array variable(done)
  5. write content in log file (.csv) created on PC from where the script is being executed.

Issue is script getting details, but when trying to write to log its not writing and giving error "Cannot index into a null array."

my code is below:

$servers = gc .\servers.txt
$Global:ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$date = (get-date).ToString("yyyyMMdd_HHmm")
$ILOContent = "$ScriptDir\ILOConfigData_$date.csv"
Add-Content -Path $ILOContent -Value "ILO_Name,ILO_Domain,Network_Details,ILO-TimeZone,Directory_Users,LDAP_Directory_Authentication,Directory_Groups,SNMP-Settings,Directory_Server_Address"


Foreach($server in $servers){

        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" 
                    & "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|Set-Content "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 DNS details"
                    $DNS_NAME = $ILO_DATA |Where {$_ |Select-String -Pattern " DNS_NAME VALUE"," DOMAIN_NAME VALUE"}
                    $ILONAME = $DNS_NAME -split "="
                    $ServerILO = $ILONAME[1]
                    $ILONAME[3]

                    Write-Host "Getting 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.Trim()

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

                    #DIRECT
                    Write-Host "Getting 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 ; $DIR_USERS = [Array]$User -join "`n"

                    
                    Write-Host "getting Global:ScriptDir location"
                    Set-Location $Global:ScriptDir
                    Get-Location
                    $Data = $ILONAME[1]+$ILONAME[3]+$Network,$Model,$TimeZone[1],$DIR_USERS
                    $Data|Select-Object $ILONAME[1],$ILONAME[3],$Network,$TimeZone[1],$DIR_USERS |Export-Csv -Append -Path $ILOContent -notypeinformation                                                        

 }
 }

As commented, I think it's a bad idea to parse properties from an XML file using textual methods.
Better let PowerShell parse it for you and pick the properties you need:

$date      = (Get-Date).ToString("yyyyMMdd_HHmm")
$scriptDir = Split-Path $MyInvocation.MyCommand.Path
$outFile   = "$ScriptDir\ILOConfigData_$date.csv"
$servers   = Get-Content -Path .\servers.txt

$result = foreach ($server in $servers) {
    Write-Host "Gathering current ILO configuration for '$server'" 
    Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
        & "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w `
          "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" | Out-Null
    
        # load the xml the hponcfg.exe just created (PowerShell will parse it for you)
        $config = New-Object -TypeName System.Xml.XmlDocument
        $config.Load("C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml")

        # preselect the nodes for DIR_USER_CONTEXT_1, DIR_USER_CONTEXT_2 etc.
        $userContext = $config.HPONCFG.MOD_DIR_CONFIG.ChildNodes | Where-Object {$_.Name -like 'DIR_USER_CONTEXT*' }

        # output a PSObject to be collected in variable $config
        [PsCustomObject] @{
            Server             = $env:COMPUTERNAME
            DNSName            = $config.HPONCFG.MOD_NETWORK_SETTINGS.DNS_NAME.VALUE
            DomainName         = $config.HPONCFG.MOD_NETWORK_SETTINGS.DOMAIN_NAME.VALUE
            IPAddress          = $config.HPONCFG.MOD_NETWORK_SETTINGS.IP_ADDRESS.VALUE
            SubnetMask         = $config.HPONCFG.MOD_NETWORK_SETTINGS.SUBNET_MASK.VALUE
            GateWay            = $config.HPONCFG.MOD_NETWORK_SETTINGS.GATEWAY_IP_ADDRESS.VALUE
            PrimaryDnsServer   = $config.HPONCFG.MOD_NETWORK_SETTINGS.PRIM_DNS_SERVER.VALUE
            SecondaryDnsServer = $config.HPONCFG.MOD_NETWORK_SETTINGS.SEC_DNS_SERVER.VALUE
            TertiaryDnsServer  = $config.HPONCFG.MOD_NETWORK_SETTINGS.TER_DNS_SERVER.VALUE
            TimeZone           = $config.HPONCFG.MOD_NETWORK_SETTINGS.TIMEZONE.VALUE
            UserContext        = $userContext.Value -join [environment]::NewLine
        } 
    }
}

$result | Export-Csv -Path $outFile -NoTypeInformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM