1

I've used Invoke-Restmethod to download some data, which Powershell stores in a PSCustomObject, in a property called data.

I need to use the value of one of the items in the returned data as a variable for another command. I have managed to select-object -expand my way down to the following output from Get-Member:

Name        MemberType   Definition                    
----        ----------   ----------                    
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()             
GetType     Method       type GetType()                
ToString    Method       string ToString()             
id          NoteProperty System.Int32 id=999 

What I need to do is grab the value of the ID noteproperty - 999 - and pass that as part of a string to a new variable, eg:

$newVar = "sometext" + 999 + "moretext"

No amount of select-string or out-string etc is helping. Scripting is not exactly my strong point so I'm not sure I'm even articulating what I want properly - apologies if this is the case!

Any assistance much appreciated

2 Answers 2

2

I'm not sure exactly what your code and looks like, so I created the following static approximation from the description:

$data = New-Object PSCustomObject
$data | Add-Member -Type NoteProperty -Name Id -Value 999
$restResponse = New-Object PSCustomObject
$restResponse | Add-Member -Type NoteProperty -Name data -Value $data

Please clarify if this is not a match. You can get the Id value as follows

$restResponse.data.Id

Assign it to another variable

$newVar = "sometext" + $restResponse.data.Id + "moretext"
$newVar

And if your REST response is a collection of data objects, iterate through them

$restResponse.data | Foreach-Object { "sometext" + $_.Id + "moretext" }
Sign up to request clarification or add additional context in comments.

1 Comment

Thats done it, thank you. I think I was staring at this for too long!
0

I would go for for using $output | select *,@{n='test';e={[string]$_.test}} -exclude properties test

if the exclude is not active it will complain about it already exists. Mostly I use the select expression to manipulate data realtime instead of psCustomObject for such simple task

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.