[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.
반응형
'ICT' 카테고리의 다른 글
[Windows10] Enable Microsoft Store (0) | 2023.08.24 |
---|---|
JavaScript Learning Pathway (0) | 2023.08.11 |
[PowerShell] Adding Values in Group Policy via PowerShell (0) | 2023.07.04 |
[Windows 10] How to Deal with RSAT Installation Error (0) | 2023.06.29 |
[VBA] Extracting Data from SQL with a Button in Excel (0) | 2023.06.27 |
댓글