I want to get all childs from Object in powershell script.
I have :
$task = [system.Text.Encoding]::UTF8.GetString((Invoke-WebRequest -Uri "url" -Method GET -ContentType "application/json" -Header $headers).RawContentStream.ToArray()) | ConvertFrom-Json
so $task
is an object who contains property tasks
and these tasks have tasks...
like:
$task : {
[
{
id: 1,
name: "post question",
status: "FAILED",
tasks: [
{
id: 10,
name: "post answer",
status: "PLANNED",
tasks: [
{
}
]
},
{
id: 20,
name: "post answer",
status: "FAILED",
tasks: [
{
id: 50,
name: "any text",
status: "PASS",
tasks: [
{
}
]
}
]
}
]
},
{
id: 2,
name: "Load question",
status: "SUCCESS",
tasks: [
{
id: 30,
name: "post answer",
status: "PLANNED",
tasks: [
{
}
]
}
]
}
]
}
How can I get all tasks
from all tasks
... from my $task
thanks in advance.
Your Json is not completely correct, so I needed to tweak it a little:
$Tasks = ConvertFrom-Json @'
[
{
id: 1,
name: "post question",
status: "FAILED",
tasks: [
{
id: 10,
name: "post answer",
status: "PLANNED",
tasks: [
{
}
]
},
{
id: 20,
name: "post answer",
status: "FAILED",
tasks: [
{
id: 50,
name: "any text",
status: "PASS",
tasks: [
{
}
]
}
]
}
]
},
{
id: 2,
name: "Load question",
status: "SUCCESS",
tasks: [
{
id: 30,
name: "post answer",
status: "PLANNED",
tasks: [
{
}
]
}
]
}
]
'@
The recursive function is actually quite simple:
Function Get-Tasks($Tasks) {
ForEach($Task in $Tasks) {
If ($Task.id) {$Task | Select-Object id, name, status}
If ($Task.Tasks) {Get-Tasks $Task.Tasks}
}
}
Get-Tasks $Tasks
Result:
id name status
-- ---- ------
1 post question FAILED
10 post answer PLANNED
20 post answer FAILED
50 any text PASS
2 Load question SUCCESS
30 post answer PLANNED
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.