Framework/Listeners/UserReports/WriteDataFile.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
Set-StrictMode -Version Latest 
class WriteDataFile: FileOutputBase
{   
    hidden static [WriteDataFile] $Instance = $null;
    hidden [int] $JsonDepth = 10;

    static [WriteDataFile] GetInstance()
    {
        if ( $null -eq  [WriteDataFile]::Instance)
        {
            [WriteDataFile]::Instance = [WriteDataFile]::new();
        }
    
        return [WriteDataFile]::Instance
    }

    [void] RegisterEvents()
    {
        $this.UnregisterEvents();       

        $this.RegisterEvent([AzSKRootEvent]::GenerateRunIdentifier, {
            $currentInstance = [WriteDataFile]::GetInstance();
            try 
            {
                $currentInstance.SetRunIdentifier([AzSKRootEventArgument] ($Event.SourceArgs | Select-Object -First 1));            
            }
            catch 
            {
                $currentInstance.PublishException($_);
            }
        });

        $this.RegisterEvent([SVTEvent]::CommandStarted, {
            $currentInstance = [WriteDataFile]::GetInstance();
            try 
            {
                $currentInstance.SetFilePath($Event.SourceArgs.SubscriptionContext, [FileOutputBase]::ETCFolderPath, ("SecurityEvaluationData-" + $currentInstance.RunIdentifier + ".json"));
            }
            catch 
            {
                $currentInstance.PublishException($_);
            }
        });
        
        $this.RegisterEvent([SVTEvent]::CommandCompleted, {
            $currentInstance = [WriteDataFile]::GetInstance();
            try 
            {
                $currentInstance.WriteToJson($Event.SourceArgs);
                $currentInstance.FilePath = "";
            }
            catch 
            {
                $currentInstance.PublishException($_);
            }
        });

    }

    [void] WriteToJson([SVTEventContext[]] $arguments)
    {
        if ([string]::IsNullOrEmpty($this.FilePath)) {
            return;
        }

        if($arguments)
        {
            if (($arguments | Measure-Object).Count -gt 0) 
            {                
                [Helpers]::ConvertToJsonCustom($arguments) | Out-File $this.FilePath
                #[Helpers]::ConvertToPson($arguments) | Out-File $($this.FilePath.Replace(".json", ".pson"))
            }
        }
    }
}