Powershell with .NET

Last updated: 2013-07-31

This post is where I want to put howto do things from .NET in powershell. As time went by it turned out  I also wanted to add powershell howtos in general.

You might also checkout some other of my powershell blogs for tips

Just powershell:

Errorhandling when calling powershell cmdlets

$?: Did last operation succeed?
$error[0]: Latest error
$error[1]: Before latest error – maybe an innerexception
Link: An Introduction to Error Handling in PowerShell

if ($?){
    Write-Host "  [OK]" -ForegroundColor Green
    Write-Host "Error (might be empty): $error[0].ErrorDetails" -ForegroundColor Red
    Write-Host "Possible innerexception: $error[1].Exception.Message" -ForegroundColor Red

Supporting -WhatIf

Ed Wilson explains how to support -whatif in a cmdlet. It seems like it is available from v3.

function my-function{
 md $path

Add CRLF to strings

$crlf = "`n`r"
$Body = "Testing CRLF:" + $crlf
$Body += "Bla-bla"

Set current directory to the dir, where this script resides

function Get-ScriptDirectory{
	$Invocation = (Get-Variable MyInvocation -Scope 1).Value
	Split-Path $Invocation.MyCommand.Path

	#Maybe this would work, too:
	Split-Path $MyInvocation.MyCommand.Path
cd (Get-ScriptDirectory)


There are some automatic conversions, that makes code different from .NET.

Using string.Split()

[char]$domsep = '\'
[string]$userid = "CONTOSO\XANDH"
#Split will in .NET accept a char[], but here it is OK to give the char directly without the array
$userid = $userid.Split($domsep)[1] #XANDH
#In most cases you can use the powershell way to do split as below, but that does not work, when the split char is '\'
#$userid = ($userid -split "\")[1] #XANDH
#In case of split char is '\' you need to escape it with an extra '\' as follows:
$userid = ($userid -split "\\")[1] #XANDH

Using String.IsNullOrEmpty()

if (-not [System.string]::IsNullOrEmpty($someString))

#You might also just want to check if object exist
if ($someObject)

Newing up a .NET object

… including constructor parms …

$cred = new-object net.NetworkCredential($ENV:USERNAME, $global:pass, $ENV:USERDOMAIN)



Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: