Removing item form JSON in powershell - powershell

I got a question to ask for removing an object in Json in powershell. I am fetching my results from powershell and i compressed it and placed into a JSON as shown below
foreach ($vm in $vms) {
$id = $vm.Config.InstanceUuid
$vmname = $vm.Config.Name
$geturl = "https://$nsxmanager/api/v1/fabric/virtual-machines?external_id=$id&included_fields=tags"
$getrequest = Invoke-RestMethod -Uri $geturl -Authentication Basic -Credential $nsxtcred -Method Get -ContentType "application/json" -SkipCertificateCheck
$getresult = $getrequest.results | ConvertTo-Json -Compress
Write-Host ($getresult)
}
This will get the results
{"tags":[{"scope":"allow_access","tag":"external"}, {"scope":"test","tag":"text"}]}
{"tags":[{"scope":"allow_access","tag":"external"}]}
{"tags":[{"scope":"allow_access","tag":"external"}]}
{"tags":[{"scope":"allow_access","tag":"external"}]}
{"tags":[{"scope":"allow_access","tag":"external"}]}
{"tags":[{"scope":"allow_access","tag":"external"}]}
{"tags":[{"scope":"allow_access","tag":"external"}]}
I am trying to remove the element {"scope":"allow_access","tag":"external"} from all these results.
im not sure how i can remove it and wanted to seek some advice here how can I do so ?

You can try filtering out these results by converting your JSON results to a PSCustomObject, iterating through the Tags attribute in a nested Foreach loop, and building a new PSCustomObject that does not contain those results you would like to filter:
$getresult = $getresult | ConvertFrom-Json
$FilteredTagsArr = #()
Foreach($Tag in $GetResult.Tags){
If($Tag.scope -eq 'allow_access' -and $Tag.tag -eq "external"){
#Do Nothing
}Else{
$NewObj = [PSCustomObject]#{
Tag = $tag.tag
Scope = $tag.scope
}
$FilteredTagsArr += $NewObj
}
}
$GetResult.Tags = $FilteredTagsArr
Return $GetResult | ConvertTo-Json

Related

How to time delay between each url in a PowerShell http server status check script

I am using the following PS script to check the server status of a list of URLs.
$linksFilePath = "C:\Temp\urls.txt"
$outCSVPath = "C:\Temp\results.csv"
get-content $linksFilePath |
Foreach { $uri = $_; try { Invoke-WebRequest -Uri $uri -Method HEAD -MaximumRedirection 0 -ErrorAction SilentlyContinue -UseBasicParsing } catch {
New-Object -TypeName psobject -Property #{ Error = $_ } } } |
Select #{Name="RequestURI";Expression={$uri}}, StatusCode, #{Name="RedirectTo";Expression={$_.Headers["Location"]}}, Error |
Export-Csv $outCSVPath
I want the script to pause for x amount of seconds between each url in my urls.txt list before moving on to the next line and append the results to my results.csv file accordingly.
Is this possible?

FreshAgent Get Asset Data

I am trying to fetch asset data from the Fresh client with Powershell. I am able to get any asset by typing it's name but I want to save some of the variables it returns so I can use it further.
$naam = Read-Host "Voer product naam in"
# Set global variables
$APIKey = 'Myapikey'
$EncodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $APIKey,$null)))
$HTTPHeaders = #{ "X-ApiKey" = $APIKey}
$HTTPHeaders.Add('Authorization', ("Basic {0}" -f $EncodedCredentials))
$HTTPHeaders.Add('Content-Type', 'application/json')
$URL = 'https://helpdesk.company.nl/cmdb/items/list.json?field=name&q='+$naam
(Invoke-WebRequest -Method Get -Uri $URL -Headers $HTTPHeaders ).content
The following are some of the values that return after I run the above
{"config_items":[{"id":25000477949,"name":"SYS-MB1334","description":null,"ci_type_id":25000015988,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"
I would like to save the name and id variable for example
Unfortunately, the JSON you show is invalid.
Suppose the json returned from
$output = (Invoke-WebRequest -Method Get -Uri $URL -Headers $HTTPHeaders ).Content
looks like:
{"config_items":
[{"id":25000477949,"name":"SYS-MB1334","description":null,"ci_type_id":25000015988,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"},
{"id":12345678901,"name":"SYS-MB9876","description":null,"ci_type_id":12358745896,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"}]
}
Then you can collect the properties you need from the config_items using:
$result = ($output | ConvertFrom-Json).config_items |
Select-Object #{Name = 'Id'; Expression = {$_.id}},
#{Name = 'Name'; Expression = {$_.name}}
# output on screen
$result
# output to CSV file
$result | Export-Csv -Path 'X:\TheOutput.csv' -NoTypeInformation
Output on screen would look like
Id Name
-- ----
25000477949 SYS-MB1334
12345678901 SYS-MB9876
Hope that helps

Looping through array and returning results of each object in Powershell

I need some help with the following PS code:
$site1 = "www.site1.com"
$site2 = "www.site2.com"
$site3 = "www.site3.com"
$sites = $site1,$site2,$site3
$request = foreach ($site in $sites) {invoke-webrequest $site -method head}
if ($request.StatusCode -ne "200"){write-host "site is not working"}
The actual output of $request returns the headers of all 3 sites, so how do I get the exact site that failed the test?
Thanks in advance
Try something like this:
"www.site1.com","www.site2.com", "www.site3.com" |
ForEach-Object {
$response = Invoke-WebRequest $_ -Method Head
[PsCustomObject]#{
Site = $_
StatusCode = $response.StatusCode
}
}
You can filter the output by appending the following after the last bracket:
| Where-Object StatusCode -ne 200

Make Invoke-WebRequest loop through each URL it finds

I'm new to PowerShell and I'm trying to make the Invoke-WebRequest cmdlet loop through each url the webscrape finds. All I have so far is this :
$site = Invoke-WebRequest -UseBasicParsing -Uri www.example.com/examples
$site.Links | Out-GridView
Any help would be appreciated!
Add your links to a comma separated list.
Split the list and loop each item.
Request each item.
As below:
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$urlCollection = "link1,link2,link3"
$separator = ","
$urlList = $urlCollection.Split($separator, $option)
foreach ($url in $urlList) {
Invoke-WebRequest $url
# Give feedback on how far we are
Write-Host ("Initiated request for {0}" -f $url)
}

Access SharePoint expanded properties

I'm accessing a SharePoint lists has an associated stakeholder entity--I'm having difficultly accessing the stakeholder's properties.
The 'primary' content's properties are located on xpath /feed/entry/content/properties/*. The stakeholder's properties are located on xpath /feed/entry/link/inline/entry/content/properties/*.
Assuming that I include the stakeholder's name in the odata query:
http://server/list/_vti_bin/listdata.svc/TheList?$select=Id,Title,Stakeholder/Name&$expand=Stakeholder
How do I reference the stakeholder's properties when enumeration the feed's properties?
Using this code, the Stakeholder.Name property is not populated:
(Invoke-RestMethod -Uri $url -Method Get -UseDefaultCredentials).entry.content.properties | Foreach {
[PsCustomObject]#{
Id=$_.Id."#text";
Title=$_.Title;
StakholderName=$_.Stakeholder.Name;
}
}
Do I need to populate a second PsCustomObject for the stakeholder, then merge the 'primary' data?
The query is malformed since $ symbol have to be escaped using single-quoted string literals, for example:
$url = "http://contoso.intranet.com/_vti_bin/listdata.svc/TheList?`$select=Id,Title,Stakeholder/Name&`$expand=Stakeholder"
Then Stakeholder value could retrieved as demonstrated below:
$StakeholderValue = $data.link | where { $_.title -eq "Stakeholder" } | select -Property #{name="Name";expression={$($_.inline.entry.content.properties.Name)}}
Modified example
$url = "http://contoso.intranet.com/_vti_bin/listdata.svc/TheList?`$select=Id,Title,Stakeholder/Name&`$expand=Stakeholder"
$data = Invoke-RestMethod -Uri $url -Method Get -UseDefaultCredentials -ContentType "application/json;odata=verbose"
$data | Foreach {
[PsCustomObject]#{
Id = $_.content.properties.Id."#text";
Title = $_.content.properties.Title;
Stakeholder = $_.link | where { $_.title -eq "Stakeholder" } | select -Property #{name="Name";expression={$($_.inline.entry.content.properties.Name)}}
}
}
Alternatively i would propose to consider another approach. By default SharePoint 2010 REST service returns results in xml format. The idea is to return results in json format instead.
Unfortunately neither Invoke-RestMethod nor
Invoke-WebRequest could not be utilized for that purpose
since both of them contain a bug in PowerShell 3.0 according to
Microsoft Connect.
This particular bug prevents us to consume SharePoint REST services since
since Accept header could not be specified and therefore results could not
be returned in json format
Having said that, i would recommend to leverage WebClient Class.
Below is demonstrated the same example that returns results in JSON format. Note that getting of List Item properties become a way easier compared to the original example :
Function Execute-RequestJson()
{
Param(
[Parameter(Mandatory=$True)]
[string]$Url,
[Parameter(Mandatory=$False)]
[System.Net.ICredentials]$Credentials,
[Parameter(Mandatory=$False)]
[bool]$UseDefaultCredentials = $True,
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get
)
$client = New-Object System.Net.WebClient
if($Credentials) {
$client.Credentials = $Credentials
}
elseif($UseDefaultCredentials){
$client.Credentials = [System.Net.CredentialCache]::DefaultCredentials
}
$client.Headers.Add("Content-Type", "application/json;odata=verbose")
$client.Headers.Add("Accept", "application/json;odata=verbose")
$data = $client.DownloadString($Url)
$client.Dispose()
return $data | ConvertFrom-Json
}
$url = "http://contoso.intranet.dev/_vti_bin/listdata.svc/TheList?`$select=Id,Title,Stakeholder/Name&`$expand=Stakeholder"
$data = Execute-RequestJson -Url $url -UseDefaultCredentials $true
$data.d.results | Foreach {
[PsCustomObject]#{
Id = $_.Id;
Title = $_.Title;
Stakeholder = $_.Stakeholder.Name
}
}