16

For example I have a PSObject transaction with two properties: id and transactionName , so that it looks like: transaction { id: 123 transactionName : tranName1 }

and I want to return the id of the transaction if its name is tranName1.

It looks to me that in powershell scripts, we can simply do:

if $transaction.transactionName -eq tranName return $transaction.id

however in c# it will give error since it cannot recognize the property by name... any ideas how to do it in c#?

jamesdeath123
  • 4,268
  • 11
  • 52
  • 93
  • Possibly because the property name is `transactionName`? – p.s.w.g Mar 07 '13 at 17:54
  • @p.s.w.g even I corrected the name it won't work, because C# knows transaction as PSObject, which does not contain a member of "transactionName"... – jamesdeath123 Mar 07 '13 at 18:31
  • There is no C# code posted. Anyway, just find the type, then [*look at the documentation*](http://msdn.microsoft.com/en-us/library/system.management.automation.psobject.aspx) for basic ideas of how to use it .. however, I suspect that using a correctly-typed "transaction" value to begin with would be more useful. –  Mar 07 '13 at 18:46
  • @pst Mike Shepard provided the solution to my answer :) thank you though for sharing :) – jamesdeath123 Mar 07 '13 at 19:12

2 Answers2

39

Try something like this:

psobjectvariable.Properties["transactionName"].Value
Mike Shepard
  • 17,466
  • 6
  • 51
  • 69
  • I know this is an old reply but, what about subproperties, for example: $transaction.transactionName.propertyA – Roberto Jun 21 '16 at 15:29
  • 2
    @Roberto If `propertyA` is a PSObject you can do like this: `((PSObject)psobjectvariable.Properties["transactionName"].Value).Properties["propertyA"]` – Patrick Aug 25 '16 at 07:17
  • @Patrick doesn't cast, please... You'll get an error. Try: `PSObject.AsPSObject`. – rios0rios0 Jul 21 '21 at 21:36
4

Here's something that I didn't expect to work, but it did.

dynamic x = psobjectvariable;
Console.Write(x.transactionName);
Ambrose Leung
  • 3,704
  • 2
  • 25
  • 36