/\/\o\/\/ PowerShelled

This blog has moved to http://ThePowerShellGuy.com Greetings /\/\o\/\/
$AtomFeed = ("Atom.xml")
$PreviousItems = (" Wipe the screen in MSH "," Blog series about Errorhandling in MSH "," This Month's line-break and Pipelines are Back "," [msh]cd.. "," MSH start. Function "," Argggg "," Where are my pipelines "," WMI help Part 3 (Methods) "," WMI help Part 2 "," Wmi-Help Part 1 "," ")

Friday, November 11, 2005

 


Exploring .NET types, classes and Enums from MSH



the .NET framework has some very handy Classes,Some of them are "wrapped" by MSH CMDlets, making them "native" MSH commands but only a small subset.

*Edit* (did add the pipelines again hope I got them All)

but you also have access to the other .NET classes from MSH,You can initalize a .NET object with new-object like this :

$Obj = Namespace.classname

So as an Example a class the could be handy some times is the .NET Stopwatch class (hmmm, could you guess what that class should be doing ?)
In this case I think with some trying you would be able to get it working, but you can imagine that is not the case with all .NET Objects ;-)
But as you see below you can get the Members of the Class with the Get-Member function, so that you can find out what the class does.


MSH>$sw = new-object System.Diagnostics.Stopwatch
MSH>$sw.start()
MSH>$sw.stop()
MSH>$sw

IsRunning Elapsed ElapsedMilliseconds ElapsedTicks
--------- ------- ------------------- ------------
False 00:00:06.1038371 6103 18312549030


MSH>$sw | gm


TypeName: System.Diagnostics.Stopwatch

Name MemberType Definition
---- ---------- ----------
Equals Method System.Boolean Equals(Object obj)
get_Elapsed Method System.TimeSpan get_Elapsed()
get_ElapsedMilliseconds Method System.Int64 get_ElapsedMilliseconds()
get_ElapsedTicks Method System.Int64 get_ElapsedTicks()
get_IsRunning Method System.Boolean get_IsRunning()
GetHashCode Method System.Int32 GetHashCode()
GetType Method System.Type GetType()
Reset Method System.Void Reset()
Start Method System.Void Start()
Stop Method System.Void Stop()
ToString Method System.String ToString()
Elapsed Property System.TimeSpan Elapsed {get;}
ElapsedMilliseconds Property System.Int64 ElapsedMilliseconds {get;}
ElapsedTicks Property System.Int64 ElapsedTicks {get;}
IsRunning Property System.Boolean IsRunning {get;}


MSH>



But there also some .NET classes that are static, this means they have no constructor (a New-Method) so you can not use get-object to make an Object from it.

an example of a very handy Static .NET class (also refered to as Type) is the System.Math Class, but as you can see the new-Object does not work.

MSH>$m = new-object system.math
new-object : Constructor not found. Cannot find an appropriate constructor for type system.math.
At line:1 char:16

But there is another way of accessing Static .Net Classes, as in caling the Power Operator as is shown below


MSH>[system.math]::pow(2,32)
4294967296
MSH>[system.math] | gm


TypeName: System.RuntimeType

(as system is already "imported" by MSH in this case [math]::pow(2,32)would be enough, but mostly you must use the namespaces too)

but If you Use Get-Member to get the Members of the Class, a strange thing happens, you get the members of the System.Runtype Class (I did cut out the member-output, but as you can see if you try this yourself, there are a lot of them but none related to the Math class.
the Trick is you have to use the -Static parameter of get-Member(GM) to get the methods on a static class. (this makes sence since as it is a Static class it has now Object to act upon, hence it has only static Members, only I this it is confusing that you get a system.runtype class back)


MSH>[system.math] | gm -static


TypeName: System.Math

Name MemberType Definition
---- ---------- ----------
Abs Method static System.Single Abs(Single value), static Sy...
Acos Method static System.Double Acos(Double d)
Asin Method static System.Double Asin(Double d)
Atan Method static System.Double Atan(Double d)
Atan2 Method static System.Double Atan2(Double y, Double x)
BigMul Method static System.Int64 BigMul(Int32 a, Int32 b)
Ceiling Method static System.Double Ceiling(Double a), static Sy...
Cos Method static System.Double Cos(Double d)
Cosh Method static System.Double Cosh(Double value)
DivRem Method static System.Int32 DivRem(Int32 a, Int32 b, Int3...
Equals Method static System.Boolean Equals(Object objA, Object ...
Exp Method static System.Double Exp(Double d)
Floor Method static System.Double Floor(Double d), static Syst...
IEEERemainder Method static System.Double IEEERemainder(Double x, Doub...
Log Method static System.Double Log(Double d), static System...
Log10 Method static System.Double Log10(Double d)
Max Method static System.SByte Max(SByte val1, SByte val2), ...
Min Method static System.SByte Min(SByte val1, SByte val2), ...
Pow Method static System.Double Pow(Double x, Double y)
ReferenceEquals Method static System.Boolean ReferenceEquals(Object objA...
Round Method static System.Double Round(Double a), static Syst...
Sign Method static System.Int32 Sign(SByte value), static Sys...
Sin Method static System.Double Sin(Double a)
Sinh Method static System.Double Sinh(Double value)
Sqrt Method static System.Double Sqrt(Double d)
Tan Method static System.Double Tan(Double a)
Tanh Method static System.Double Tanh(Double value)
Truncate Method static System.Decimal Truncate(Decimal d), static...
E Property static System.Double E {get;}
PI Property static System.Double PI {get;}


then another .net type the Enum :

Sometimes a Method thakes a Enum as an Input Parameter, as example I will take the
set_foreGound of the $host object of MSH (if you read some of the previous posts, you might notice I like to play with this Object ;-), also it makes a good example of the difference between working with objects or classes / types as this Method come from the .NET system.console class as you will see in the Example.


MSH>$host


Name : ConsoleHost
Version : 1.0.60319.0
InstanceId : 73fe5c33-31b9-4a9b-93d7-ff53183509cf
UI : System.Management.Automation.Internal.Host.InternalHostUserI
nterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData :



MSH>$host.ui.rawui


ForegroundColor : Gray
BackgroundColor : Black
CursorPosition : 0,980
WindowPosition : 0,920
CursorSize : 25
BufferSize : 80,9999
WindowSize : 80,61
MaxWindowSize : 80,77
MaxPhysicalWindowSize : 160,77
KeyAvailable : False
WindowTitle : /\/\o\/\/SH - C:\Documents and Settings\mow



MSH>$host.ui.rawui.set_ForegroundColor.OverloadDefinitions
System.Void set_ForegroundColor(ConsoleColor value)
MSH>


The MSH shell has a $host variable that is standard filled with the MSH console Object.A interesting SubObject is the UI.RawUI that let's us play with the MSH Console,and coming back to our subject that RawUI object (as you see later this is actualy an instance of (a parent class of) system.console).
This Method takes an ConsoleColor as an inputParameter, so how do we find out what the heck that is, and what are the possibe values ?

I will show some different way's : (below I pasted some MSH output with linenumbers, so you can lookup the Example Quickly)

1) just putting something in, (LINE 1)

in this case an INT (this was my first reaction as I thought most enums are based on numbers.This does not work but the error does say that it is expecting a system.consoleColor, so we know a bit more now as this looks as a .NET class.

2) do an SDK lookup or google :

http://msdn2.microsoft.com/en-us/library/system.consolecolor.aspx
(as it is a new enum in .NET 2.0 you need the msdn2 site (as 2.0 is RTM I don't know for how long, it was a bit empty still at that time)

3) Use the COlor we did lookup in the SDK (LINE 6)

Afer a bit of trying I could add the color as string behind the enumname as a string (casting the string to the Enum)

4) Make a wrong try (Line 8)
as I was trying I found a way to get the possible values without a SDK lookup, Just use a noneexisting colorname ;-)

for some time I used this method and the colors not easy to use, but sometimes the .NET classnames are a bit Long,as i got a bit more used to static classes and enums I found some more possibilities :

Using an Enum
- use :: (LINE 7 )
- Put it in a Variable first (this will sometime confuse the parser)
- use just the string (MSH will cast it to the Enum, I was very hapy when I found out this one.) (Forgot it in the sample, but it will work just try)

Getting the Possible Colors

- Using the system.enum getNames Method (LINE 16)
- Get-Member -static (as here we have the same problem as with the static classes the just GM returns the runtype, it took me a while to find this way) (LINE 33)


  1 MSH>$host.ui.rawui.set_ForegroundColor(1)
2 Cannot convert argument "0", with value: "1", for "set_ForegroundColor" to type
3 "System.ConsoleColor".
4 At line:1 char:35
5 + $host.ui.rawui.set_ForegroundColor( <<<< 1)
6 MSH>$host.ui.rawui.set_ForegroundColor([system.consoleColor]"Red")
7 MSH>$host.ui.rawui.set_ForegroundColor([system.consoleColor]::gray)
8 MSH>$host.ui.rawui.set_ForegroundColor([system.consoleColor]"purple")
9 Cannot convert "purple" to "System.ConsoleColor" due to invalid enumeration val
10 ues. The possible enumeration values are "Black, DarkBlue, DarkGreen, DarkCyan,
11 DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Mage
12 nta, Yellow, White".
13 At line:1 char:57
14 + $host.ui.rawui.set_ForegroundColor([system.consoleColor]" <<<< purple")
15 MSH>$host.ui.rawui.set_ForegroundColor("Red")
16 MSH>[system.enum]::getnames([ConsoleColor])
17 Black
18 DarkBlue
19 DarkGreen
20 DarkCyan
21 DarkRed
22 DarkMagenta
23 DarkYellow
24 Gray
25 DarkGray
26 Blue
27 Green
28 Cyan
29 Red
30 Magenta
31 Yellow
32 White
33 MSH>[system.consoleColor] | gm -static
34
35
36 TypeName: System.ConsoleColor
37
38 Name MemberType Definition
39 ---- ---------- ----------
40 Equals Method static System.Boolean Equals(Object objA, Objec...
41 Format Method static System.String Format(Type enumType, Obje...
42 GetName Method static System.String GetName(Type enumType, Obj...
43 GetNames Method static System.String[] GetNames(Type enumType)
44 GetUnderlyingType Method static System.Type GetUnderlyingType(Type enumT...
45 GetValues Method static System.Array GetValues(Type enumType)
46 IsDefined Method static System.Boolean IsDefined(Type enumType, ...
47 Parse Method static System.Object Parse(Type enumType, Strin...
48 ReferenceEquals Method static System.Boolean ReferenceEquals(Object ob...
49 ToObject Method static System.Object ToObject(Type enumType, Ob...
50 Black Property static System.ConsoleColor Black {get;}
51 Blue Property static System.ConsoleColor Blue {get;}
52 Cyan Property static System.ConsoleColor Cyan {get;}
53 DarkBlue Property static System.ConsoleColor DarkBlue {get;}
54 ....
55


as Final some tips and some more Diffences between GM on static classes or on objects
AS I mentioned before $rawUi inherits from system.console, so we are also able to change the collor by using static methods of system.console.

but as you can see below we are not only limited by haveing to use GM - static

LINE 1 : this will change the Consolecolor Just like $host

LINE 2 : this will give NO output

LINE3 : As with an Object this works

LINE 15 : this also does not work with a static Object

LINE 17 : This the only workaround I have for Now (still the overloads are on one line so not so readable.

if you have a method with alot of overloads, you realy miss the Overload Definition.


  1 MSH>[system.console]::set_ForegroundColor("gray")
2 MSH>[system.console]::set_ForegroundColor
3 MSH>$host.UI.RawUI.set_ForegroundColor
4
5
6 MemberType : Method
7 OverloadDefinitions : {System.Void set_ForegroundColor(ConsoleColor value)}
8 TypeOfValue : System.Management.Automation.MshMethod
9 Value : System.Void set_ForegroundColor(ConsoleColor value)
10 Name : set_ForegroundColor
11 IsInstance : True
12
13
14
15 MSH>$host.UI.RawUI.set_ForegroundColor.OverloadDefinitions
16 System.Void set_ForegroundColor(ConsoleColor value)
17 MSH>[system.console] | gm -static fl


another strange thing with GM is that if you ask the properties of a Collecton, you have to put a , before it (see also Strange behavour of get-member on DataTables and here Create System Variable From MSH )

I hope this will help a it exploring .NET from MSH, as there are some tricky quirks you have to take care of when using GM on static classes, but there real powerfull tools to have acces to from the MSH CLI !

gr /\/\o\/\/


Comments:
Blogger Sung Meister
Pipe "|" isn't being displayed again.
 
Blogger /\/\o\/\/
Yes. I did see, A did all the typing in HTML Mode then did a paste of a link and the pipelines where gone again, as it was a long type, and there no real code, I leave it as is.

sorry for that, but I have to find the places in HTML code and that is not Fun. ;-(

I'm will take a look at the Mail and Word posters for blogger when I have time, I did choose for a blog not a Site to be less concerned with the lay-out LOL

I will Alway's repair the Scripts I post, I hope for the sample most PPL will get it.

thx for remarking.

gr /\/\o\/\/
 
Blogger Sung Meister
hey, np there.. and thanks for more blogs :)
 
Post a Comment



<< Home

Archives

October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006  

$Links = ("PowerShell RC1 Docs"," PowerShell RC1 X86"," PowerShell RC1 X64"," Monad GettingStarted guide"," Monad Progamming Guide"," Monad SDK"," Monad videos on Channel 9"," MSH Community Workspace"," scripts.readify.net "," MonadSource"," www.reskit.net"," PowerShell Blog"," Under The Stairs"," computerperformance powershell Home"," proudlyserving"," MSH on wikipedia"," MSHWiki Channel 9"," Keith Hill's Blog"," Precision Computing"," PowerShell for fun"," MSH Memo (Japanese)"," monadblog")

find-blog -about "PowerShell","Monad" | out-Technorati.
find-blog -contains "","" | out-Technorati.
Google
 
Web mow001.blogspot.com

This page is powered by Blogger. Isn't yours?