Pergunta

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

Foi útil?

Solução

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" }

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top