简体   繁体   中英

C# to Powershell InvokeMember

How would I write the following C# code in Powershell?

m_object.GetType().InvokeMember(sPropertyName, m_flgGetProperty, null, m_object, null)

Almost exactly the same way you do in C#. For example, this is how you would get the Length property from a string (if for some reason you had to do it this way):

$m_object = "some string"
$sPropertyName = "Length"
$m_flgGetProperty = [Reflection.BindingFlags] "DeclaredOnly, Public, NonPublic, Instance, GetProperty"

$m_object.GetType().InvokeMember($sPropertyName, $m_flgGetProperty, $null, $m_object, $null)

The differences from C#:

  1. Variables all start with $ .
  2. Refer to types with their full namespace (although System is not needed), enclosed in [] .
  3. To combine enum flags into a single value (like for the BindingFlags ), you can use the comma-separated list like above instead of | . PowerShell converts the strings into the enum values for you.

PowerShell natively allows for dynamic invocation to a degree, so assuming the type member is public , it might be as simple as:

$PropertyName = 'MemberName'
$object.$PropertyName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM