Use PowerShell to test your code – part I

PowerShell
One of the advantages PowerShell has over other scripting languages is that it can run .NET code and load .NET objects natively. VBScript could do the same only with a .NET registered as COM object (Regasm – ed).
You can use notepad/notepad++ to write your code but I recommend the much better PowerGUI which is specifically written for PowerShell and includes plenty of useful snippets that can ease your code writing, especially if you are lazy enough to learn a new syntax but rather focused on completing an intense task.
image
Some code might resemble Bash and some is  more c – like
To run the script, first disable the security restrictions:
run this: Set-ExecutionPolicy Unrestricted
You can also set it in the registry:
HKLM\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" 
set "ExecutionPolicy" to "RemoteSigned" or "Unrestricted"

image
Add-Type Cmdlet can actually do more than just adding a new type definition.
If you use it with an –AssemblyName parameter, it will allow you to load an existing .NET assembly and run some unit tests, there is no need to create a project in visual studio and to recompile each time you want a small change in code.
With PowerShell – all you need to do is to change the string on the fly.

Remember – there is no way to get rid of a loaded type other than restarting the PowerShell session.

It is also possible to load all the types in an assembly this way:
[System.Reflection.Assembly]::LoadFrom("C:\test.dll");

If you’re familiar with CodeDom, you would probably notice that in a smilar way PowerShell can even compile your code and generate a valid DLL/EXE assembly.

Don’t want the code in your PS script?
Load it and compile:
$fileWithCode = “c:\test.cs”
$code = [System.IO.File]::ReadAllText($fileWithCode)
Add-Type – TypeDefinition $code
We’ve seen how to call a static member of a class, but what if we want to create an instance of it?
$instance = New-Object Tests
or
$instance = New-Object –ArgumentsList $one,$two

PowerShell manual is very extensive and explains well the meaning of each parameter. Use “get-help [CmdLet]” to get a description of the action.

Post a Comment

Previous Post Next Post