본문 바로가기
ICT

[PowerShell] PSCustomObject for Saving Log

by NeoSailer 2023. 7. 14.

[Scenario]

The business wants a scipt to run periodically as a temporal solution and needs to trace script's activities via log.

 

[Objectives]

Create PSCustomObject to save script log as an Excel file

 

[Steps]

As starter, lets create PSCustomObject which can save datetime, device, action

$pso = [PSCustomObject]@{
    "DateTime" =(get-date -format 'yyyy-MM-dd')
    "DeviceName" ='KRYAN-L-FM992H2'
    "State"='UNLOCK'
}

$pso

DateTime   DeviceName      State 
--------   ----------      ----- 
2023-07-14 KRYAN-L-FM992H2 UNLOCK

'[PSCustomObject]' declares data type and '@{...}' clarifies hash table. As it is required to data underneath a certain column hashtable is a proper format to save a log.

 

However, hash table cannot store multiple entities.

$pso += [PSCustomObject]@{
    "DateTime" =(get-date -format 'yyyy-MM-dd')
    "DeviceName" ='KRYAN-L-FM992H2_copy'
    "State"='LOCK'
} 

[System.Management.Automation.PSObject]에 이름이 'op_Addition'인 메서드가 없으므로 메서드를 호출하지 못했습니다.
위치 줄:1 문자:1
+ $pso += [PSCustomObject]@{
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

 

 Let's create an array and add data in form of hash table.

$arr = @()

$arr += [PSCustomObject]@{
    "DateTime" =(get-date -format 'yyyy-MM-dd')
    "DeviceName" ='KRYAN-L-FM992H2'
    "State"='UNLOCK'
}
$arr += [PSCustomObject]@{
    "DateTime" =(get-date -format 'yyyy-MM-dd')
    "DeviceName" ='KRYAN-L-FM992H2_copy'
    "State"='LOCK'
}

$arr

DateTime   DeviceName           State 
--------   ----------           ----- 
2023-07-14 KRYAN-L-FM992H2      UNLOCK
2023-07-14 KRYAN-L-FM992H2_copy LOCK

 

Looks fancy!

 

As the last step, let's save the array as an Excel file.

$arr = @()

for($i = 0; $i -lt 3; $i++)
{
    $arr += [PSCustomObject]@{
    "DateTime" =(get-date -format 'yyyy-MM-dd')
    "DeviceName" ='KRYAN-L-FM992H2'
    "State"='UNLOCK'
    }
    
    $arr += [PSCustomObject]@{
        "DateTime" =(get-date -format 'yyyy-MM-dd')
        "DeviceName" ='KRYAN-L-FM992H2_copy'
        "State"='LOCK'
    }
}
$arr | export-csv -path "c:\temp\pso.csv" -NoTypeInformation -Append

Works well.

반응형

댓글