Skip to main content

Using Text Based Logs with Windows PowerShell (7 of 8)


Day 7: Creating an object template
 
Yesterday we extracted a dynamic list of property names from our log file.  Today we will complete step 3: Create an object that contains all possible property names.
The object that we are creating is going to contain all of our properties with values set to $Null.  That way we will have a template without any restrictions on the data type that the properties will hold.
    Function New-EmptyObject
    {
    Param ($PropList)
    # Creates an empty object to be used for each instance of the final
    # object. This ensures a consistent set of members for the object.
       
        $Obj = New-Object -TypeName psobject
      
        # Change the type name.
        $Obj.pstypenames.insert(0,'Custom.LogObject')
      
        ForEach ($P in $Proplist.Prop)
        {
            $Obj | Add-Member -NotePropertyName "$($P)" `
                              -NotePropertyValue $Null
        } # End: ForEach ($P in $Proplist.Prop)
     
        # Return the object to the calling statement.
        Write-Output $Obj
    } # End Function New-EmptyObject
 
Here we are feeding the function New-EmptyObject our $Proplist object.  The function creates an empty object called $Obj and then changes the object type from System.Management.Automation.PSCustomObject  to Custom.LogObject.  Custome.LogObject is our own, unique object type. Next each property from the $PropList is added as a property of the object with a value set to $Null.  Once this is completed, the object is returned and stored as $EmptyObject.
 
Here is the code:
 
Function Import-MyLog2
{
    # -----------------------------------------------------------------------
    Function Get-Log
    {
    # Reads the log file into memory.  Will display an error if the
    # file cannot be found.
 
        Try
        {
            Get-Content -path "\\Server1\Log\Data2.txt" `
                        -ErrorAction Stop |
            Write-Output
        }
        Catch
        {
            Write-Error "The data file is not present"
            BREAK
        }
    } # End: Function Get-Log
    # -----------------------------------------------------------------------
    Function Get-RecordIndex
    {
    Param ($Log)
    # Determines the index number of where each record starts and ends.
    # Returns an object with the start and end index number of
    # each record.
 
        # Array to hold all of the objects.
        $Object = @()
       
        # Find the start of each record.
        For($X=0;$X -lt $Log.Count; $X++)
        {
            If($Log[$X] -like "Server Blade #* Information:")
            {
 
                $Obj = New-Object -TypeName PSObject
                $Obj | Add-Member -NotePropertyName "Start" `
                                  -NotePropertyValue $X
                $Obj | Add-Member -NotePropertyName "End" `
                                  -NotePropertyValue $Null
                $Object += $Obj
            }
        } # End: For($X=0;$X -lt $Log.Count; $X++)
 
        # Derive the end of each record.
        For ($X = 0; $X -lt $Object.Count - 1; $X++)
        {
            $Object[$X].End = $Object[$X+1].Start -1
        } # End: For ($X = 0; $X -lt $Object.Count; $X++)
 
        # Add the final End value as the end of the log file.
        $Object[$Object.count-1].End = $Log.count
 
        # Return the object to the calling statement.
        Write-Output $Object
       
    } # End: Function Get-RecordIndex
    # -----------------------------------------------------------------------
    Function Format-PropertyName
    {
    Param ($Name)
    # Used to get the proper name format for the list of properties and also
    # While creating the actual data for the final objects.
 
        $Value = $Name.Trim()
        $Pos = $Value.IndexOf(":")
        Write-Output $Value.Substring(0,$Pos).Replace(" ","")
               
    } # End: Function Format-PropertyName
    # -----------------------------------------------------------------------
    Function Get-PropertyList
    {
    Param($RecordIndex, $Log)
    # To help build a more flexible object, we need to identify possible
    # property names.  This function will cycle through each record and use
    # a rule to identify the name of a property.  Our rule is any string
    # other than the string that starts the record that starts with blank
    # characters, has text, and the it will end at the first ":".  All spaces
    # in the property names will also be removed.
       
        # Array to hold all of the objects.
        $Object = @()
 
        ForEach ($R in $RecordIndex)
        {
            For ($X=$R.Start+1;$X -lt $R.End;$X++)
            {
 
                # Examine only lines from the record that are not blank.
                If (($Log[$X].length -gt 0) -and ($Log[$X] -like "*:*"))
                {
                    $Obj = New-Object -TypeName PSObject
                    $Obj | Add-Member -MemberType NoteProperty `
                                      -Name "Prop" `
                                      -Value (Format-PropertyName -Name $Log[$X])
                   $Object += $Obj                
                }
            } # End: For ($X=$R.Start;$X -lt $R.End;$X++)
        } # End: ForEach ($R in $RecordIndex)
 
        # Add the "Slot" property to record the slot number.
        $Obj = New-Object -TypeName PSObject
        $Obj | Add-Member -MemberType NoteProperty `
                            -Name "Prop" `
                            -Value "Slot"
        $Object += $Obj
        # Filter the list of protential properties to make sure that they
        # are all unique.
        $Object = $Object | Select-Object -Property Prop -Unique
 
        # Return the object to the calling statement.
        Write-Output $Object
 
    } # End: Function Get-PropertyList
    # -----------------------------------------------------------------------
    Function Get-Record
    {
    Param ($Log,$RecordIndex)
       
        # Array to hold all of the objects.
        $Object = @()
 
        ForEach($R in $RecordIndex)
        {
            $Obj = New-Object -TypeName PSObject
            $String = $Null
            For($X=$R.Start;$X -lt $R.End; $X++)
            {
                $String += $Log[$X]
            }
            $Object += $String  
        }
       
        # Return the object to the calling statement.
        Write-Output $Object
 
    } # End: Function Get-Record
    # -----------------------------------------------------------------------
    Function New-EmptyObject
    {
    Param ($PropList)
    # Creates an empty object to be used for each instance of the final
    # object. This ensures a consistent set of members for the object.
       
        $Obj = New-Object -TypeName psobject
      
        # Change the type name.
        $Obj.pstypenames.insert(0,'Custom.LogObject')
      
        ForEach ($P in $Proplist.Prop)
        {
            $Obj | Add-Member -NotePropertyName "$($P)" `
                              -NotePropertyValue $Null
        } # End: ForEach ($P in $Proplist.Prop)
     
        # Return the object to the calling statement.
        Write-Output $Obj
    } # End Function New-EmptyObject
    # -----------------------------------------------------------------------
    # Load the log into memory
    $Log = Get-Log
 
    # Extract the records
    $RecordIndex = Get-RecordIndex -Log $Log
 
    # Extract the propertyl list.
    $PropList = Get-PropertyList -RecordIndex $RecordIndex -Log $Log
 
    # Create an empty object to use as our template using our $PropList.
    $EmptyObj = New-EmptyObject -PropList $PropList
    $EmptyObj # This line will be removed.  It shows our current progress.
 
} #End: Function Import-MyLog1
 
Here is our output:
 
ServerBladeType                  :
Type                             :
Manufacturer                     :
ProductName                      :
PartNumber                       :
SystemBoardSparePartNumber       :
SerialNumber                     :
UUID                             :
ServerName                       :
AssetTag                         :
ROMVersion                       :
CPU1                             :
CPU2                             :
Memory                           :
NIC1                             :
NIC2                             :
NIC3                             :
NIC4                             :
iSCSI1                           :
iSCSI2                           :
Mezzanine2                       :
Port1                            :
Port2                            :
ManagementProcessorInformation   :
Name                             :
FirmwareVersion                  :
IPAddress                        :
MACAddress                       :
PowerManagementControllerVersion :
FLBAdapter1                      :
EthernetFlexNIC(NIC1)LOM1        :
EthernetFlexNIC(NIC3)LOM1        :
EthernetFlexNIC(NIC5)LOM1        :
EthernetFlexNIC(NIC7)LOM1        :
EthernetFlexNIC(NIC2)LOM1        :
EthernetFlexNIC(NIC4)LOM1        :
EthernetFlexNIC(NIC6)LOM1        :
EthernetFlexNIC(NIC8)LOM1        :
Slot                             :  
 
 
Tomorrow we will finish up and tie everything together.

Comments

Popular posts from this blog

Sticky Key problem between Windows Server 2012 and LogMeIn

This week I instructed my first class using Windows Server 2012 accessed via LogMeIn and discovered a Sticky Key problem every time you press the Shift key. Here is my solution to resolve this.  First off, in the Preferences of LogMeIn for the connection to the Windows Server, click General . Change the Keyboard and mouse priority to Host side user and click Apply at the bottom. On the Windows 2012 server, open the Control Panel – Ease of Access – Change how your keyboard works . Uncheck Turn on Sticky Keys . Click Set up Sticky Keys . Uncheck Turn on Sticky Keys when SHIFT is pressed five times . Click OK twice. If you are using Windows Server 2012 as a Hyper-V host, you will need to redo the Easy of Use settings on each guest operating system in order to avoid the Sticky Key Problem. Updated Information: March 20, 2013 If you continue to have problems, Uncheck Turn on Filter Keys .

Where did a User’s Account Get Locked Out?

Updated: May 15, 2015 When this article was originally published, two extra carriage returns were add causing the code to malfunction.  The code below is correct.   My client for this week’s PowerShell class had a really interesting question. They needed to know where an account is being locked out at. OK, interesting. Apparently users hop around clients and forget to log off, leading to eventual lock out of their accounts. The accounts can be unlocked, but are then relocked after Active Directory replication. This problem is solved in two parts. The first one is to modify the event auditing on the network. The second part is resolved with PowerShell. The first part involves creating a group policy that will encompass your Domain Controllers. In this GPO, make these changes. Expand Computer Configuration \ Policies \ Windows Settings \ Security Settings \ Advanced Audit Policy Configuration \ Audit Policies \ Account Management Double click User Account Management C...

Backup and Restore AD LDS with DSDBUTIL.exe

Active Directory Lightweight Directory Services allow you to create a directory service that allows applications to have access to user accounts, groups, and authentication similar to Active Directory Domain Services.  The big advantage here is that the schema of the directory service will not be bound by the rules of an Active Directory database.  Exchange 2007/2010, for example, use an instance of AD LDS on the Edge Transport Server to provide for user authentication from the internet.  Because your Active Directory database is not exposed to the internet, this is more secure. Applications will handle most of the dirty work should they require AD LDS.  You may want to make sure the database is being backed up and also have a restore plan in place.  Should the database become corrupt, the application that uses that database will fail.  This document will walk you through backing up and restoring an instance of AD LDS using the dsdbutil.exe command. Fi...