Pages

Saturday, July 23, 2016

PowerShell: Explore .NET Classes 101

In this first PowerShell post, I will go over how to access .NET classes via PowerShell. This will allow you to understand the basics of .NET classes, and how PowerShell object-oriented functionality works. I will start with some requirements for this quick exercise and a couple of definitions as always.

Requirements
  • At least Windows 7
  • At least PowerShell V2

.NET Framework 101


It is a managed execution environment that provides a variety of services to its running applications. It consists of two major components: The Common Language Runtime (CLR), which is the execution engine that handles running applications, provides memory management and other system services; and the .NET Framework Class Library, a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services.


  • The Common Language Runtime (CLR)
    You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness.
     

  • .NET Framework Class Library
    Besides being a collection of reusable types that integrate with the common language runtime, it is object oriented providing types which your own managed code can develop functionality from. 
    As you would expect from an object-oriented class library, the .NET Framework types enable you to accomplish a range of common programming tasks, including tasks such as string management, data collection, database connectivity, and file access. 
    • Types
      • All types in the .NET framework are either value types or reference types
      • Value Types are data types whose objects are represented by the object's actual value.Value types include the following:
        • All numeric data types
        • Boolean, Char, and Date
        • All structures, even if their members are reference types
        • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
      • A reference type contains a pointer to another memory location that holds the data. Reference types include the following:
        • Structures
        • Classes
        • Enumerations
        • Interfaces
        • Delegates


.NET Framework Naming Conventions

  • .NET Framework types use a dot syntax naming scheme that connotes a hierarchy.
  • This technique groups related types into namespaces so they can be searched and referenced more easily.
  • The first part of the full name  up to the rightmost dot — is the namespace name. The last part of the name is the type name.




    • In this example, System.Net.Sockets represents the Sockets type, which is part of the System.Net namespace.
    • This specific type provides a managed implementation of the Windows Sockets (Winsock) interface.
    • Remember that Reference Types also contain structures, Delegates, Enumerations and Interfaces. For the purpose of this blog, I am showing only Classes. 


PowerShell & .NET Classes
  • In order to access/utilize known .NET classes via PowerShell, you have to use the CMDLET New-Object, the parameter -TypeName, specify the .NET Class and save the return value (.NET object) to a variable.

    Syntax:
       $variable = New-Object  -TypeName <.NET Class/Reference Type>
  • Several .NET Classes require parameters so you will need to add the parameter that it requires in order to explore its methods and properties
  • You can then see the methods and properties that the class presents by piping the contents of the .NET variable/Object and using the CMDLET Get-Member


PS C:\Users\wardog> $TCPClient = New-Object -Typename System.Net.Sockets.TcpClient
PS C:\Users\wardog> $TCPClient | get-member


   TypeName: System.Net.Sockets.TcpClient

Name                MemberType Definition
----                ---------- ----------
BeginConnect        Method     System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCallback, System.Object state), System.IAsyncResult BeginConnect(ipaddress address, int port, System.AsyncCallback requestCallback, System.Object state)...
Close               Method     void Close()
Connect             Method     void Connect(string hostname, int port), void Connect(ipaddress address, int port), void Connect(System.Net.IPEndPoint remoteEP), void Connect(ipaddress[] ipAddresses, int port)
ConnectAsync        Method     System.Threading.Tasks.Task ConnectAsync(ipaddress address, int port), System.Threading.Tasks.Task ConnectAsync(string host, int port), System.Threading.Tasks.Task ConnectAsync(ipaddress[] addresses, int port)
Dispose             Method     void Dispose(), void IDisposable.Dispose()
EndConnect          Method     void EndConnect(System.IAsyncResult asyncResult)
Equals              Method     bool Equals(System.Object obj)
GetHashCode         Method     int GetHashCode()
GetStream           Method     System.Net.Sockets.NetworkStream GetStream()
GetType             Method     type GetType()
ToString            Method     string ToString()
Available           Property   int Available {get;}
Client              Property   System.Net.Sockets.Socket Client {get;set;}
Connected           Property   bool Connected {get;}
ExclusiveAddressUse Property   bool ExclusiveAddressUse {get;set;}
LingerState         Property   System.Net.Sockets.LingerOption LingerState {get;set;}
NoDelay             Property   bool NoDelay {get;set;}
ReceiveBufferSize   Property   int ReceiveBufferSize {get;set;}
ReceiveTimeout      Property   int ReceiveTimeout {get;set;}
SendBufferSize      Property   int SendBufferSize {get;set;}
SendTimeout         Property   int SendTimeout {get;set;}



  • This specific example will be useful when we build a TCP Server-Client infrastrucutre with .NET classes
  • You can see that the TcpClient Class has a method named Connect. This can be used to connect to a Server Socket , and as you can see, under the definitions column, Connect calls for (String Hostname, int port)

    Example:  

    $TcpClient = New-Object System.Net.Sockets.TcpClient
    $TcpClient::Connect(localhost, 8000)


  • Another way to access Reference Types (Classes) is by going through the assemblies (Collection of types and resources) available in the current PowerShell session and filtering the output by public types only.
  • In order to accomplish this we will have to use the AppDomain.GetAssemblies Method (), use its GetTypes() method and pipe the results to a condition where we specify only the types that are Public. 


PS C:\Users\wardog> $PublicTypes = ([AppDomain]::CurrentDomain.GetAssemblies()).gettypes() | Where-Object {$_.IsPublic -eq "True"}
PS C:\Users\wardog> $PublicTypes | Where-Object {$_.Name -eq "Process"}

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Process                                  System.ComponentModel.Component


PS C:\Users\wardog> $NetClass = $PublicTypes | Where-Object {$_.Name -eq "Process"}
PS C:\Users\wardog> $NetClass | get-member -MemberType Method -Static


   TypeName: System.Diagnostics.Process

Name               MemberType Definition
----               ---------- ----------
EnterDebugMode     Method     static void EnterDebugMode()
Equals             Method     static bool Equals(System.Object objA, System.Object objB)
GetCurrentProcess  Method     static System.Diagnostics.Process GetCurrentProcess()
GetProcessById     Method     static System.Diagnostics.Process GetProcessById(int processId, string machineName), static System.Diagnostics.Process GetProcessById(int processId)
GetProcesses       Method     static System.Diagnostics.Process[] GetProcesses(), static System.Diagnostics.Process[] GetProcesses(string machineName)
GetProcessesByName Method     static System.Diagnostics.Process[] GetProcessesByName(string processName), static System.Diagnostics.Process[] GetProcessesByName(string processName, string machineName)
LeaveDebugMode     Method     static void LeaveDebugMode()
new                Method     System.Diagnostics.Process new()
ReferenceEquals    Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
Start              Method     static System.Diagnostics.Process Start(string fileName, string userName, securestring password, string domain), static System.Diagnostics.Process Start(string fileName, string arguments, string userName, securestring password, string do...



  • As you can see on the example above, after getting only the assemblies loaded on the current PowerShell session, I looked for the assembly named process.
  • That pointed us to the Reference Type or .NET Class "System.Diagnostics.Process". From there I can continue investigating and find out what specific properties or methods it has.
  • In order to make it easy and start using the Class, I only ask for methods that are static.


  • Now, lets use our .NET class and one of its methods (Start)

PS C:\Users\wardog> $NetClass | get-member -MemberType Method -Static


   TypeName: System.Diagnostics.Process

Name               MemberType Definition
----               ---------- ----------
EnterDebugMode     Method     static void EnterDebugMode()
Equals             Method     static bool Equals(System.Object objA, System.Object objB)
GetCurrentProcess  Method     static System.Diagnostics.Process GetCurrentProcess()
GetProcessById     Method     static System.Diagnostics.Process GetProcessById(int processId, string machineName), static System.Diagnostics.Process GetProcessById(int processId)
GetProcesses       Method     static System.Diagnostics.Process[] GetProcesses(), static System.Diagnostics.Process[] GetProcesses(string machineName)
GetProcessesByName Method     static System.Diagnostics.Process[] GetProcessesByName(string processName), static System.Diagnostics.Process[] GetProcessesByName(string processName, string machineName)
LeaveDebugMode     Method     static void LeaveDebugMode()
new                Method     System.Diagnostics.Process new()
ReferenceEquals    Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
Start              Method     static System.Diagnostics.Process Start(string fileName, string userName, securestring password, string domain), static System.Diagnostics.Process Start(string fileName, string arguments, string userName, securestring password, string do...


PS C:\Users\wardog> $NetClass::Start("cmd.exe", "/K ping google.com")

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id  SI ProcessName
-------  ------    -----      ----- -----   ------     --  -- -----------
      6       4     1392       1276 ...63     0.00  10040   1 cmd









  • As you can see, I was able to use the Process() .NET Class and one of its methods Start() in order to start a process from my PowerShell session. 
  • I was able to understand the syntax of the specific method by reading the definition's column and it was asking me to provide at least the FileName/Executable and the Argument for the specific process in a String Format..
    • I decided to start Command Prompt and execute "/K ping google.com"
      • /K -  Which means "Run command and return to the CMD prompt. Do not Terminate CMD"


I hope this basic introduction to exploring .NET Classes via PowerShell was useful and got you interested on finding more about other classes available for you via the shell (So many !). There is a lot you can do with them. All it takes is curiosity and creativity. 


References:


https://msdn.microsoft.com/en-us/library/zw4w595w(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/zcx1eb1e(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx- 
https://msdn.microsoft.com/en-us/library/ms973231.aspx
https://msdn.microsoft.com/en-us/library/hfa3fa08(v=vs.110).aspx

No comments:

Post a Comment