I'm trying to create a PSCustomObject that will later on be converted to JSON as the body of an API request.
This body basically has a structure to add / remove different information to a security management tool policy (filehash / filenames / certificates / IPs / file extensions / folders exceptions, on which technology etc.)
Here is an example of a final JSON with all the possibilities. As a proof of concept, I'm focusing on the following part which is adding a filename & a filehash to the exception policy
{
"add": {
"applications": [
{
"processfile": {
"sha2": "6ddc5c11925ab348eb0d390ec5179c1d655eb4bf70779f7a4e28b7db485d20ea",
"name": "myfilename"
}
}
]
...
My goal is not to import this specific JSON as a custom Object, (I know this can be done through convertfrom-Json). It's to create some empty object, but with the correct structure matching the JSON format. This way, I would just have to populate and access information in my object like this :
PS C:\PSSymantecCloud> $obj.add.applications
processfile
-----------
@{sha2=6ddc5c11925ab348eb0d390ec5179c1d655eb4bf70779f7a4e28b7db485d20ea; name=myfilename}
PS C:\PSSymantecCloud> $obj.add.applications.processfile
sha2 name
---- ----
6ddc5c11925ab348eb0d390ec5179c1d655eb4bf70779f7a4e28b7db485d20ea myfilename
I've been trying to play around with Format-Custom CmdLet but without success. Any suggestions on how to create such a custom PSObject ?
CodePudding user response:
I'm fond of PowerShell classes so here is one way to do it with them. You can add new processfile
with the AddProcessFile
method that takes 2 arguments as in your Json:
class addjson {
[object] $add
addjson() {
$this.add = [pscustomobject]@{
applications = [System.Collections.Generic.List[object]]::new()
}
}
[void] AddProcessFile([string] $sha2, [string] $name) {
$this.add.applications.Add([pscustomobject]@{
processfile = [pscustomobject]@{
sha2 = $sha2
name = $name
}
})
}
}
$add = [addjson]::new()
$add.AddProcessFile('6ddc5c11925ab348eb0d390ec5179c1d655eb4bf70779f7a4e28b7db485d20ea', 'myFile')
$add.AddProcessFile('6ddc5c11925ab348eb0d390ec5179c1d655eb4bf70779f7a4e28b7db485d20ea', 'myFile2')
$add | ConvertTo-Json -Depth 4
Resulting Json would be:
{
"add": {
"applications": [
{
"processfile": {
"sha2": "6ddc5c11925ab348eb0d390ec5179c1d655eb4bf70779f7a4e28b7db485d20ea",
"name": "myFile"
}
},
{
"processfile": {
"sha2": "6ddc5c11925ab348eb0d390ec5179c1d655eb4bf70779f7a4e28b7db485d20ea",
"name": "myFile2"
}
}
]
}
}
CodePudding user response:
Create an psObject shell, assign empty strings ““, or $false to the properties
$Object = New-Object PSObject -Property @{
Name = ““
SecondProperty= ““
yetAnotherProoerty= ““
}
Later u can assign your results like this:
$Object.name= $myResult
Or even add new member aka properties to the object like this:
Object | Add-Member -NotePropertyName Status -NotePropertyValue Done