Powershell Simplified Part 9: Powershell Tips

Some Powershell tips and tricks to make your life easier,

1. Working with write-host,

write-host "starting "nonewline          # don't add a new line after the string
write-host "iexplore.exe" -foregroundcolor red -backgroundcolor yellow  # change text color
write-host "`nIs a new line`n"             # `n is a new line
write-host "`tIs a tab"                    # `t is a tab
write-host ("{0} : {1}" -f "formatting a string", "works!")    # format a string
write-host "this is a double-quote `""
write-host "this is a single-quote '" 

2. Powershell also has an equivalent of C#’s string literal, called here-string,

$a = @"
This can have any char: ``~!@#$%^&*()_+{}|\;'"<>?[]/     # note that ` needs to be escaped with another `
write-host $a

3. To get the current script name,

write-host $MyInvocation.MyCommand.Name         # get current script name
write-host $MyInvocation.MyCommand.Definition   # get current script full directory 

4. Sometimes we need to suppress a Powershell cmd output,

$path = "c:\program files\internet explorer\signup\test"
new-item $path -itemtype directory              # will output some extra information to stdout

# to suppress the output, try one of these,
new-item $path -itemtype directory > $null      # preferred way
new-item $path -itemtype directory | out-null
$null = new-item $path -itemtype directory
[void] (new-item $path -itemtype directory) 

5. Strings and variable/expression expansions,

$a = "test"
write-host 'this is a $a'            # single-quote won't expand the variable
write-host "this is a $a"            # only double-quotes will process variable substitutions 

$file = get-item $env:windir\explorer.exe
write-host "file version: $file.versioninfo.productversion"        # variables get expanded in strings not property expressions
write-host "file version: $($file.versioninfo.productversion)"     # use $() for expression expansion 

6. Getting keyboard input,

write-host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") 
write-host "Pressed $($x.character)"
switch($x.virtualkeycode) {           # for special keys, map the virtualkeycode,
    13 { write-host "Enter" } 
    16 { write-host "Shift" } 

7. We can add custom C# types to Powershell using add-type. However add-type has a limitation that once you load an assembly into a .NET application, the types it contains are not released until the application shuts down, so running the sample below again will result in "Add-Type : Cannot add type. The type name ‘myClass’ already exists."

add-type -typedefinition @" 
  using System;
  public class myClass { 
      private string _test = "He said: "; 
      private static string test = "She said: ";

      public string Test { 
          get { return this._test; } 
          set { this._test = value; } 

      public string DoSomething(string str) { 
          return this.Test + str; 

      public static string DoSomethingElse(string str) { 
          return test + str; 

[myClass]::DoSomethingElse("test")   # invoke the static method
$a = new-object myClass
$a.DoSomething("test")               # invoke the instance method

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

2 Responses to Powershell Simplified Part 9: Powershell Tips

  1. Pingback: Powershell Simplified Series « I.Net

  2. 86Sally says:

    I see you don’t monetize your website, don’t waste your traffic, you can earn additional bucks every month because you’ve
    got high quality content. If you want to know how to make extra bucks, search for: best adsense alternative Wrastain’s tools

Leave a Reply

Fill in your details below or click an icon to log in:

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: