PowershellでTypeからメンバーを取得する

.netのクラスは取得できた。
http://d.hatena.ne.jp/junjun777/20140115/powershell_search_type
しかし、コンストラクターがわからない。
から、インスタンスのメンバーがわからない、という事態が発生する。


そこで、また関数を書いてみた。



関数

function Get-TypeMember() {
	Param(
		$Target,
		[switch]$Static,
		[switch]$Private
	)

	if($Target -is [String]) {
		if($Target -match '^\[[^\]]+]$') {
			$Target = (($Target -replace '^\[([^\]]+)]$', '$1') -as [type])
		} else {
			$ts = (Get-Types $Target)
			if($ts -ne $null -and -not $ts.length) {
				$Target = $ts
			} elseif(!$ts.length) {
				Write-Error ($Target + ' is not found!')
				$Target = $null
			} else {
				$ts | %{ Write-Host ('[' + $_.FullName + ']') }
				return Get-TypeMember (Read-Host ?)
			}
		}
	}

	$res = @()
	if($Target -is [Type]) {

		function getMembersSub($tar, [string]$para, [string]$pre) {
			function getTypeName($type) {
				$res = $type.ToString()
				$res = $res -replace 'System.Boolean', 'bool'
				$res = $res -replace 'System.String', 'string'
				$res = $res -replace 'System.Int32', 'int'
				$res = $res -replace 'System.Char', 'char'
				return $res
			}

			$res = @()
			foreach($mi in $tar.GetMembers($para)) {
				$def = ''
				if(-not $mi.IsPublic -and ($mi.MemberType -ne 'Property' -and $mi.MemberType -ne 'NestedType')) { $def = '# ' }
				$def += $pre
				$type = $mi.MemberType.ToString()
				switch($type) {
					Method {
						$def += (getTypeName $mi.ReturnType) + ' ' + $mi.Name + '('
						$comma = $false
						foreach($pi in $mi.GetParameters()) {
							if($comma) { $def += ', ' }
							$def += (getTypeName $pi.ParameterType) + ' ' + $pi.Name
							$comma = $true
						}
						$def += ')'
					}
					Constructor {
						$type = 'CodeMethod'
						$def += $tar.Name + '('
						$comma = $false
						foreach($pi in $mi.GetParameters()) {
							if($comma) { $def += ', ' } else { $comma = $true }
							$def += (getTypeName $pi.ParameterType) + ' ' + $pi.Name
						}
						$def += ')'
					}
					Property {
						$def += (getTypeName $mi.PropertyType) + ' ' + $mi.Name
						$comma = $true
						foreach($pi in $mi.GetIndexParameters()) {
							if($comma) { $def += '('; $type = 'ParameterizedProperty'; $comma = $false } else { $def += ', ' }
							$def += (getTypeName $pi.ParameterType) + ' ' + $pi.Name
						}
						if(-not $comma) { $def += ')' }
						$def += ' {'
						if($mi.CanRead) { $def += 'get;' }
						if($mi.CanWrite) { $def += 'set;' }
						$def += '}'
					}
					Field {
						$type = 'Properties'
						$def += (getTypeName $mi.FieldType) + ' ' + $mi.Name
					}
					NestedType {
						$type = 'PropertySet'
						$def += $tar.FullName + '+' + $mi.Name
					}
				}
				$res += (New-Object Microsoft.Powershell.Commands.MemberDefinition($Target.FullName, $mi.Name, $type, $def))
				#if($type -eq 'PropertySet') { $res += (getMembersSub $mi $para $pre) }
			}
			return $res
		}

		$def = ''
		if($Static) {
			$def = 'static '
			$ts = 'Static, Public'
		} else {
			$ts = 'Instance, Public'
		}
		if($Private) { $ts += ', NonPublic' }
		$res = getMembersSub $Target $ts $def
	} elseif($Target -ne $null) {
		$res = (Get-Member -InputObject $Target)
	}

	return $res
}

都合により、Fieldは「Properties」、NestedTypeは「PropertySet」と表示されますが、だいたいGet-Memberと同じ表示となっています。

使い方

基本的にはTypeの名前を渡すと、そのメンバーを表示してくれます。

Get-TypeMember StreamReader

とかやると

   TypeName: System.IO.StreamReader

Name                      MemberType Definition
----                      ---------- ----------
Close                     Method     System.Void Close()
get_CurrentEncoding       Method     System.Text.Encoding get_CurrentEncoding()
get_BaseStream            Method     System.IO.Stream get_BaseStream()
DiscardBufferedData       Method     System.Void DiscardBufferedData()
Peek                      Method     int Peek()
Read                      Method     int Read()
Read                      Method     int Read(char[] buffer, int index, int ...
ReadToEnd                 Method     string ReadToEnd()
ReadLine                  Method     string ReadLine()
get_EndOfStream           Method     bool get_EndOfStream()
Dispose                   Method     System.Void Dispose()
ReadBlock                 Method     int ReadBlock(char[] buffer, int index,...
GetLifetimeService        Method     System.Object GetLifetimeService()
InitializeLifetimeService Method     System.Object InitializeLifetimeService()
CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateOb...
ToString                  Method     string ToString()
Equals                    Method     bool Equals(System.Object obj)
GetHashCode               Method     int GetHashCode()
GetType                   Method     System.Type GetType()
.ctor                     CodeMethod StreamReader(System.IO.Stream stream, S...
.ctor                     CodeMethod StreamReader(string path, System.Text.E...
.ctor                     CodeMethod StreamReader(System.IO.Stream stream)
.ctor                     CodeMethod StreamReader(System.IO.Stream stream, b...
.ctor                     CodeMethod StreamReader(System.IO.Stream stream, S...
.ctor                     CodeMethod StreamReader(System.IO.Stream stream, S...
.ctor                     CodeMethod StreamReader(string path)
.ctor                     CodeMethod StreamReader(string path, bool detectEn...
.ctor                     CodeMethod StreamReader(string path, System.Text.E...
.ctor                     CodeMethod StreamReader(string path, System.Text.E...
CurrentEncoding           Property   System.Text.Encoding CurrentEncoding {g...
BaseStream                Property   System.IO.Stream BaseStream {get;}
EndOfStream               Property   bool EndOfStream {get;}

てな感じ。
複数あるような名前を指定すると

Get-TypeMember FileStream
[System.IO.FileStream]
[System.IO.IsolatedStorage.IsolatedStorageFileStream]
[System.Data.SqlTypes.SqlFileStream]
?:

とか表示して、どれか聞いてくる。
ので、「[System.IO.FileStream]」とかコピペするとそれが出る。
もちろん最初から、

Get-TypeMember [System.IO.FileStream]

としても良い。


「-Private」オプションを付与すると、NonPublicなメンバーも表示します。
NonPublicなものには、Definitionに「#」が付与されています。


「-Static」オプションは、この調子でStaticメンバーも取得できるね、と思ってやったのですが

PS > Get-TypeMember BindingFlags -Static


   TypeName: System.Reflection.BindingFlags

Name                 MemberType Definition
----                 ---------- ----------
Default              Properties static System.Reflection.BindingFlags Default
IgnoreCase           Properties static System.Reflection.BindingFlags Ignore...
DeclaredOnly         Properties static System.Reflection.BindingFlags Declar...
Instance             Properties static System.Reflection.BindingFlags Instance
Static               Properties static System.Reflection.BindingFlags Static
Public               Properties static System.Reflection.BindingFlags Public
NonPublic            Properties static System.Reflection.BindingFlags NonPublic
FlattenHierarchy     Properties static System.Reflection.BindingFlags Flatte...
InvokeMethod         Properties static System.Reflection.BindingFlags Invoke...
CreateInstance       Properties static System.Reflection.BindingFlags Create...
GetField             Properties static System.Reflection.BindingFlags GetField
SetField             Properties static System.Reflection.BindingFlags SetField
GetProperty          Properties static System.Reflection.BindingFlags GetPro...
SetProperty          Properties static System.Reflection.BindingFlags SetPro...
PutDispProperty      Properties static System.Reflection.BindingFlags PutDis...
PutRefDispProperty   Properties static System.Reflection.BindingFlags PutRef...
ExactBinding         Properties static System.Reflection.BindingFlags ExactB...
SuppressChangeType   Properties static System.Reflection.BindingFlags Suppre...
OptionalParamBinding Properties static System.Reflection.BindingFlags Option...
IgnoreReturn         Properties static System.Reflection.BindingFlags Ignore...

Get-Memberでできることでした。

PS > Get-Member -InputObject ([System.Reflection.BindingFlags]) -Static


   TypeName: System.Reflection.BindingFlags

Name                 MemberType Definition
----                 ---------- ----------
Equals               Method     static bool Equals(System.Object objA, Syste...
Format               Method     static string Format(type enumType, System.O...
GetName              Method     static string GetName(type enumType, System....
GetNames             Method     static string[] GetNames(type enumType)
GetUnderlyingType    Method     static type GetUnderlyingType(type enumType)
GetValues            Method     static array GetValues(type enumType)
IsDefined            Method     static bool IsDefined(type enumType, System....
Parse                Method     static System.Object Parse(type enumType, st...
ReferenceEquals      Method     static bool ReferenceEquals(System.Object ob...
ToObject             Method     static System.Object ToObject(type enumType,...
CreateInstance       Property   static System.Reflection.BindingFlags Create...
DeclaredOnly         Property   static System.Reflection.BindingFlags Declar...
Default              Property   static System.Reflection.BindingFlags Defaul...
ExactBinding         Property   static System.Reflection.BindingFlags ExactB...
FlattenHierarchy     Property   static System.Reflection.BindingFlags Flatte...
GetField             Property   static System.Reflection.BindingFlags GetFie...
GetProperty          Property   static System.Reflection.BindingFlags GetPro...
IgnoreCase           Property   static System.Reflection.BindingFlags Ignore...
IgnoreReturn         Property   static System.Reflection.BindingFlags Ignore...
Instance             Property   static System.Reflection.BindingFlags Instan...
InvokeMethod         Property   static System.Reflection.BindingFlags Invoke...
NonPublic            Property   static System.Reflection.BindingFlags NonPub...
OptionalParamBinding Property   static System.Reflection.BindingFlags Option...
Public               Property   static System.Reflection.BindingFlags Public...
PutDispProperty      Property   static System.Reflection.BindingFlags PutDis...
PutRefDispProperty   Property   static System.Reflection.BindingFlags PutRef...
SetField             Property   static System.Reflection.BindingFlags SetFie...
SetProperty          Property   static System.Reflection.BindingFlags SetPro...
Static               Property   static System.Reflection.BindingFlags Static...
SuppressChangeType   Property   static System.Reflection.BindingFlags Suppre...

まー、タイプ数が少ないというメリットがあるか。


ちなみに、NestedTypeは+でアクセスする。

PS > Get-TypeMember [environment]


   TypeName: System.Environment

Name          MemberType  Definition
----          ----------  ----------
ToString      Method      string ToString()
Equals        Method      bool Equals(System.Object obj)
GetHashCode   Method      int GetHashCode()
GetType       Method      System.Type GetType()
SpecialFolder PropertySet System.Environment+SpecialFolder


PS > Get-TypeMember [environment+specialfolder] -Static


   TypeName: System.Environment+SpecialFolder

Name                  MemberType Definition
----                  ---------- ----------
ApplicationData       Properties static System.Environment+SpecialFolder App...
CommonApplicationData Properties static System.Environment+SpecialFolder Com...
LocalApplicationData  Properties static System.Environment+SpecialFolder Loc...
Cookies               Properties static System.Environment+SpecialFolder Coo...
Desktop               Properties static System.Environment+SpecialFolder Des...
Favorites             Properties static System.Environment+SpecialFolder Fav...
History               Properties static System.Environment+SpecialFolder His...
InternetCache         Properties static System.Environment+SpecialFolder Int...
Programs              Properties static System.Environment+SpecialFolder Pro...
MyComputer            Properties static System.Environment+SpecialFolder MyC...
MyMusic               Properties static System.Environment+SpecialFolder MyM...
MyPictures            Properties static System.Environment+SpecialFolder MyP...
Recent                Properties static System.Environment+SpecialFolder Recent
SendTo                Properties static System.Environment+SpecialFolder SendTo
StartMenu             Properties static System.Environment+SpecialFolder Sta...
Startup               Properties static System.Environment+SpecialFolder Sta...
System                Properties static System.Environment+SpecialFolder System
Templates             Properties static System.Environment+SpecialFolder Tem...
DesktopDirectory      Properties static System.Environment+SpecialFolder Des...
Personal              Properties static System.Environment+SpecialFolder Per...
MyDocuments           Properties static System.Environment+SpecialFolder MyD...
ProgramFiles          Properties static System.Environment+SpecialFolder Pro...
CommonProgramFiles    Properties static System.Environment+SpecialFolder Com...