I am writing a PowerShell function to build the JSON that will be passed to an API. I am using PowerShell 5.
The API expects a certain format and an example is below.
{
“task”: {
“status”: {
“name”: “Resolved”
},
“owner”: {
“name”: “User”
},
“comment”: “Test”
}
}
The structure of the JSON is stored in nested hash tables then piped to ConvertTo-Json and I am passing the data values through parameters.
$baseTask = @{
task = @{
comment = $Comment;
status = @{
name = $Status;
owner = @{
name = $Owner;
}
}
}
I want the function to be as dynamic as possible so I have the identifier as mandatory and then all other parameters as optional.
Param(
[Parameter(Mandatory=$true)]
$TaskID,
$Comment,
$Status,
$Owner
)
If the parameter is NULL I want to remove that element from the definition so that it doesn’t pass NULL to the API. I have the logic below.
If([String]::IsNullOrEmpty($Comment)) {
$baseTask.task.Remove(‘comment’)
}
If([String]::IsNullOrEmpty($Status)) {
$baseTask.task.Remove(‘status’)
}
If([String]::IsNullOrEmpty($Owner)) {
$baseTask.task.Remove(‘owner’)
}
This works; however if I have 50 parameters then I am going to have a lot of repetition with the null checks so I feel there must be a more dynamic way to do this ideally with some sort of loop.
I thought about a hash table with mapping between variable name and command to run, but I can’t find a way to get the name of the variable during execution.
Any help would be much appreciated.
