I am pretty new to PowerShell and have the following code:
$jsonResponse = #"
{
"departments":[{"id":81,"department":"Sales"},{"id":61,"department":"IT Support"}]
}
"#
$myCustomObject = $jsonResponse | ConvertFrom-Json
$myCustomObject.departments.department[0]
$myCustomObject.departments.department[1]
Which allows me to access elements of the customObject (converted from JSON).
What I need is the ability to loop through the object so I can access each element i.e.
object_loop
{
$myCustomObject.departments.department[x]
}
where x is the loop increment.
Sorry of this is silly question but I have googled and can't find a simple example.
Cheers for any help.
Duncs
It is as trivial as
foreach($obj in $myCustomObject.departments)
{
Write-Host ("Got" + $obj.department)
}
Related
How to call API inside function. this is my url https://www.gov.uk/bank-holidays.json. I am new for powershell can you help me to do this.
function Holiday {
$list = Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json
Write-Host "$list"
}
but i am unable to list . can u please help me on that
Invoke-RestMethod automatically parses the API's JSON response into an object [graph] - a nested [pscustomobject] instance or an array thereof (in a manner of speaking, Invoke-RestMethod has ConvertFrom-Json built in).
While very convenient for subsequent OO processing, the resulting objects' display representation isn't very helpful:
Only the top-level properties of the object graph are printed.
Due to a long-standing bug - see GitHub issue #6163 - nested property values may falsely appear to be empty - see this answer for an example.
To quickly visualize the result, you can simply convert back to JSON, using ConvertTo-Json:
function Get-Holiday {
# Call the API, which returns JSON that is parsed into a [pscustomobject]
# graph, and return (output) the result.
Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json
}
$list = Get-Holiday
# Visualize the object for display by converting it back to JSON.
$list | ConvertTo-Json -Depth 3
Note the unfortunate need to specify -Depth 3 explicitly - see this post for background information.
An alternative visualization can be achieved by piping to Format-Custom:
The resulting for-display representation isn't JSON, but a notation that resembles hashtable literals and is easy to parse visually.
Format-Custom's default depth is 5 (compared to ConvertTo-Json's 2), so you will often get away without a -Depth argument.
Conversely, however, you may need to (temporarily) set the $FormatEnumerationLimit preference variable to ensure that all elements of a collection are visualized; by default, only 4 are, and omitted elements are represented as ….
That said, if you just want to get a quick sense of the structure of the object graph, that may not be a problem.
# Assumes that $list was obtained as above.
$list | Format-Custom
Output (showing just the first object; note the … indicating that the collection contained in the .events property has additional elements that were omitted):
class PSCustomObject
{
england-and-wales =
class PSCustomObject
{
division = england-and-wales
events =
[
class PSCustomObject
{
title = New Year’s Day
date = 2018-01-01
notes =
bunting = True
}
class PSCustomObject
{
title = Good Friday
date = 2018-03-30
notes =
bunting = False
}
class PSCustomObject
{
title = Easter Monday
date = 2018-04-02
notes =
bunting = True
}
class PSCustomObject
{
title = Early May bank holiday
date = 2018-05-07
notes =
bunting = True
}
…
]
}
With respect to processing, here's an example that accesses the first entry for England and Wales:
$list.'england-and-wales'.events[0]
The above yields:
title date notes bunting
----- ---- ----- -------
New Year’s Day 2015-01-01 True
I'm pretty stuck and can't find anything about it on the internet. I'm also not sure how to describe the thing i'm looking for, so maybe someone can help me.
I've got some code to create a ticket in TopDesk through API using invoke-restmethod in PS.
For the request field in TopDesk, I need some output stored in a variable, but if I want to use a variable in the PS command, I need to define the JSON body with the use of #{} | covertTo-JSON (found that somewhere on the internet).
Now this parameter I need to put through, has to have a definition. I need to give in in the value is a email or a name.
$json = #{
"callerLookup" = "{ email : email#domain.com }"
} | Convertto-JSON
Now the thing is, TopDesk doesn't see the "{ email : email#domain.com }" as a correct value.
Before, I just the following (which will work, but can't use variables):
$body = '{"email": "automation#rid-utrecht.nl"}'
I hope I described my problem cleary enough and hope that someone can help me.
Thanks in advance.
Kind regards,
Damian
For ConvertTo-Json to produce the serialized { "property" : "value" } syntax, you must pass it an object that has a property called property and an associated value equal to value. You can easily create this scenario with the [pscustomobject] accelerator.
$json = #{
callerLookup = [pscustomobject]#{email = 'email#domain.com'}
} | ConvertTo-Json
I am hitting a Rest API and collected a gnarly block of Json. I'm running convertfrom-json on that to get a powershell object which I would like to manipulate. Essentially I need to prune a number of field/values.
Its no issue to 'get' the fields I want to remove from the object as I can just drill down to the field and collect the value thats easy, where I am stuck is how to trim off that field from the posh object. Would appreciate any assistance. Thanks.
Example:
$sample_json = #"
{
"fields": {
"field_one": 1,
"field_two": 2,
"field_three": "three",
"field_four": "remove_me",
"field_five": 5
}
}
"#
Clear-Host
$json_object = ConvertFrom-Json -InputObject $sample_json
$json_object
Gives:
fields
------
#{field_one=1; field_two=2; field_three=three; field_four=remove_me; field_five=5}
So the question is how can I remove "field_four" key, and it's value, from $json_object ? Apologies if this is crazy simple; I'm a bit out of touch with Powershell these last few years.
You can remove "field_four" with the Remove method from PSObject.Properties:
$json_object.fields.PSObject.Properties.Remove("field_four")
Use the following statement
$json_object.fields.PSObject.Properties.Remove("field_four")
I would like to grab the 3rd "td" element in "filterTable". How is this done in a .NET environment like Powershell ? I have tried numerous ways, like so:
$_.getElementsByTagName("td")[3]
$_.getElementsByTagName("td[3]")
$_.getElementsByTagName("td:3")
$_.getElementsByTagName("td{3}")
$_.getElementsByTagName("td"){3}
However none of these seem to work. Is there a way to do this? Thanks for any help. Here is some context of my code:
$textValues = #()
$textValues = $data.ParsedHtml.getElementById("filterTable") | foreach{
$_.getElementsByTagName("td") | foreach{
$_ | Select InnerText
}
}
You can use the item() method on the element collection returned by getElementsByTagName().
Just supply an index (zero-based):
$filterTable = $data.ParsedHtml.getElementById("filterTable")
$3rdTD = $filterTable.getElementsByTagName("td").item(2)
Alternatively, use Select-Object -Index:
$filterTable.getElementsByTagName("td") |Select-Object -Index 2
I can't get my head around the piping thing. I've read through the Get-Help and in Jon Dones his examples but I can't understand it properly. So I started playing with a function I found online to execute a script block in a specific culture (regional settings).
I managed to have it process these arguments correctly:
Use-Culture de-DE {Get-Date}, {Get-TimeStamp}
Use-Culture nl-BE {Get-Date}, {Get-TimeStamp}
But when I try to pipe to Use-Culture, it's just not working at all:
de-DE {Get-Date}, {Get-TimeStamp} | Use-Culture
nl-BE {Get-Date} | Use-Culture
I feel like I'm missing the basic concept here. There was another question on StackOverlfow talking about this topic. One guy said to use Foreachand someone else said to work with -Inputobject. Then again, Don Jones used in his Advanced Function no such thing and stated that the Process block gets iterated for each object.
What is best practice to pipe multiple arguments to a function? In this case, multiple Script blocks to execute against the same Culture.
Thank you for your help as always.
Function Use-Culture {
param(
[Parameter(
Mandatory=$true,Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[System.Globalization.CultureInfo]$culture,
[Parameter(
Mandatory=$true,Position=1,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[ScriptBlock[]]$code
)
process {
ForEach ($_ in $code) {
trap {
[System.Threading.Thread]::CurrentThread.CurrentCulture = $currentCulture
}
$currentCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
[System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
Invoke-Command $_
[System.Threading.Thread]::CurrentThread.CurrentCulture = $currentCulture
}
}
}