Blog - Post List
  • Power Tips: Formatting Text Output

    If you’d like to nicely format output text, you may want to use a PSCustomObject and output it as a formatted list like so:

    $infos = [PSCustomObject]@{
        Success = $true
        Datum = Get-Date
        ID = 123
    Write-Host ($infos| Format-List | Out-String) -ForegroundColor Yellow

    Simply add and adjust keys and values in your hash table.

    Twitter This Tip! ReTweet this Tip!

    • 15 Dec 2017
  • Power Tips: Converting User Name to SID

    If you’d need to find out the SID for a user name, here is a useful chunk of code that does the job:

    $domain = 'MyDomain'
    $username = 'User01'
    $sid = (New-Object Security.Principal.NTAccount($domain, $username)).Translate([Security.Principal.SecurityIdentifier]).Value

    Just make sure you adjust domain name and username accordingly. If you need to find the SID for local accounts, set the domain…

    • 14 Dec 2017
  • Power Tips: Test-Drive PowerShell 6 – Side by Side

    PowerShell 6 can be downloaded and run side-by-side with the official Windows PowerShell. If you’d like to test-drive it, head over to, and pick the release that suits your platform.

    Be aware that it is a hefty 50MB download. After unpacking/installing the release, there will be a new PowerShell icon in all black, representing PowerShell 6. The name has changed as…

    • 13 Dec 2017
  • Power Tips: Displaying Data in a Grid View Window Vertically

    Out-GridView always produces a table with one object per line:

    Get-Process -Id $pid | Out-GridView

    Occasionally, it would be more helpful to display the object properties vertically, with one property per line in a grid view window.

    To do exactly that, take a look at Flip-Object: this function takes objects and splits them up into individual name-value-objects per property. They can then pipe to Out-GridView. This way…

    • 12 Dec 2017
  • Power Tips: Converting Information to Culture-Specific Text

    If you’d like to format information to given culture standards, this is really simple by using ToString() and the appropriate target information.

    This example takes the current Date and Time, and outputs it in French format:

    $date = Get-Date
    $frenchCulture = New-Object -TypeName CultureInfo("fr")
    $dateString = $date.ToString($frenchCulture)

    When you pick the Thai culture, you’ll notice a completely…

    • 11 Dec 2017
  • Power Tips: Converting Culture-Specific Information

    Let’s assume you received data like numbers or date as text. Whenever information is reduced to text, you are challenged with culture-specific formats: decimal point as well as date and time formats may differ between cultures.

    Here is a simple approach how you can parse data provided you know the culture where it came from:

    # number in German format
    $info = '1,2'
    # convert to real value
    $culture = New…
    • 8 Dec 2017
  • Power Tips: Understanding Text Conversions

    There are many different ways how objects can be transformed into text. In case you sometimes get confused, here is a quick refresher. Take a look:

    There are three fundamental ways how objects turn into text.

    $a = 4.5
    # simple conversion
    # slightly better conversion
    # richest conversion
    $a | Out-String

    With simple objects, the result of these methods won’t differ. With more complex objects…

    • 7 Dec 2017
  • Power Tips: Allowing PowerShell Script Execution - No Matter What

    Execution policy can prevent scripts from running. It is designed to be a user preference setting, so you should always be able to change the effective execution policy. In some environments, though, group policy forces settings on you and may prevent running scripts.

    In such a case, it might be an option for you to reset the internal PowerShell authorization manager. Once you replace it with a default instance, you can…

    • 6 Dec 2017
  • Power Tips: Comparing String Lists

    In a previous example we used HashSets to compare numeric lists, and find out which elements were found in both list, or in just one list.

    The same can be done with strings. If you have two lists with names, and would like to know which names are present in both lists, or just in one, try this:

    $set1 = New-Object System.Collections.Generic.HashSet[string] (,[string[]]@('Harry','Mary','Terri'))…
    • 5 Dec 2017
  • Power Tips: Comparing Numeric Lists

    Often a script needs to find out whether two lists are the same, or which elements are missing from a list. Instead of investing much programming work, you can resort to so-called HashSets. Have a look:

    $set1 = New-Object System.Collections.Generic.HashSet[int32] (,[int[]]@(1,2,5,7,9,12))
    $set2 = New-Object System.Collections.Generic.HashSet[int32] (,[int[]]@(1,2,5,12,111))
    "Original Sets:"
    • 4 Dec 2017
  • Power Tips: Tagging Objects Efficiently

    Occasionally you see scripts that use Select-Object to append information to existing objects. This can look similar to the code below:

    Get-Process | 
        Select-Object -Property *, Sender|
        ForEach-Object { 
            $_.Sender = $env:COMPUTERNAME

    It does work, but Select-Object creates a complete object copy, so this approach is slow and changes the object type. You’ll notice that PowerShell no longer…

    • 1 Dec 2017
  • Power Tips: Creating New Objects Efficiently

    Most of the time, the bulk of new object is static data, represented by properties. A highly efficient way to create new objects with new properties is converting hash tables to objects – we covered this earlier:

    $conf = [PSCustomObject]@{
        Name = 'Tobias'
        Conf = ''
        Url = ''

    The result is a simple object with no specific methods at all:

    PS C:\> $conf…
    • 30 Nov 2017
  • Power Tips: Adding Single Line Comments in PowerShell ISE

    In the previous tip we looked at command extensions for the good old PowerShell ISE. Here is another sample that adds the CTRL+K keyboard shortcut to append comments (“#”) to each selected line:

    function Invoke-Comment
        $file = $psise.CurrentFile                              
        $comment = ($file.Editor.SelectedText -split '\n' | ForEach-Object { "#$_" }) -join "`n"      
    • 29 Nov 2017
  • Power Tips: Toggling Comments in PowerShell ISE

    The good old PowerShell ISE exposes some expandability connectors. If you’d like to toggle comments in selected text by pressing CTRL+K, for example, try this code:

    function Toggle-Comment
        $file = $psise.CurrentFile                              
        $text = $file.Editor.SelectedText   
        if ($text.StartsWith("<#")) {
            $comment = $text.Substring(3).TrimEnd("#>") 
    • 28 Nov 2017
  • Power Tips: Converting Hash Tables to JSON

    In previous scripts we worked a lot with hash tables, and even loaded them from .psd1 files. If you need the data in a different format, for example JSON, conversion is trivial. All you need to do is convert a hash table to an object first:

    $hash = @{
      Name = 'Tobias'
      ID = 12
      Path = 'c:\windows'
    $object = [PSCustomObject]$hash
    $object | ConvertTo-Json

    Once the hash table is an object, you can…

    • 27 Nov 2017
  • Power Tips: Reading Data from .PSD1 Files in PowerShell 5+

    In a previous tip we introduced Import-LocalizedData to read in data stored in a .psd1 file.

    Starting in PowerShell 5, there is a new cmdlet named Import-PowerShellDataFile. You can use it to safely read data from a .psd1 file. Like Import-LocalizedData, this cmdlet accepts only .psd1 files with no active content (no commands or variables).

    Here is the script you need:

    $path = "$PSScriptRoot\data.psd1"
    • 24 Nov 2017
  • Power Tips: Reading Data from .PSD1 Files

    There are many ways how a script can store data information. One is especially convenient. Here is the code:

    Import-LocalizedData -BaseDirectory $PSScriptRoot -FileName data.psd1 -BindingVariable Info 

    Make sure you save the code in a script. Then, create another file in the same folder, and name it “data.psd1”, and add this content:

      Name = 'Tobias'
      ID = 12
      Path = 'c:\Windows'…
    • 23 Nov 2017
  • Power Tips: Understanding .NET Type Name Variants in PowerShell

    PowerShell can use .NET type names, for example to convert values to a given type. Frequently, scripts use a variety of formats to define .NET types. Here is why, and what they mean:

    # short name for "Integer" data type
    # official .NET type name
    # here is how you get there
    # with official names, the namespace "System" is always optional

    In short…

    • 22 Nov 2017
  • Power Tips: Minimalistic Error Handling

    Error handling does not necessarily have to be complex. It can be as simple as checking whether the last command executed successfully:

    # suppress errors by default
    $ErrorActionPreference = 'SilentlyContinue'
    # if a command runs into an error...
    Get-Process -Name zumsel
    # ...then $? is $false, and you can exit PowerShell
    # with a return value, i.e. 55
    if (!$?) { exit 55 }

    PowerShell reports back in $? whether…

    • 21 Nov 2017
  • Power Tips: Temporarily Disabling PSReadLine Module

    Beginning in PowerShell 5, the PowerShell console features colorized text, and there is a wealth of other new features provided by a module named PSReadLine.

    If you upgraded from an older PowerShell version to PowerShell 5 and are missing the colorized text, you may want to download and install PSReadLine from the PSGallery:

    PS C:\> Install-Module -Name PSReadLine -Scope CurrentUser 

    Likewise, if your PS5+ console…

    • 20 Nov 2017
  • Power Tips: Using Windows EventLog for Script Logging

    Using the built-in Windows event log architecture for script logging is great, and very simple. Here are the initial steps to prepare logging (requires Administrator privileges):

    #requires -runasadministrator
    New-EventLog -LogName PSScriptLog -Source Logon, Installation, Misc, Secret
    Limit-EventLog -LogName PSScriptLog -MaximumSize 10MB -OverflowAction OverwriteAsNeeded

    You may want to adjust the log name and/or the…

    • 17 Nov 2017
  • Power Tips: Getting File Extension

    By converting a path to a FileInfo object, you can easily determine the path parent folder or file extension. Have a look:


    Twitter This Tip! ReTweet this Tip!

    • 16 Nov 2017
  • Power Tips: Working with [FileInfo] Object

    Often, code needs to check on files, and for example test whether the file exists or exceeds a given size. Here is some commonly used code:

    $logFile = "$PSScriptRoot\mylog.txt"
    $exists = Test-Path -Path $logFile
    if ($exists)
      $data = Get-Item -Path $logFile
      if ($data.Length -gt 100KB)
        Remove-Item -Path $logFile

    By immediately converting a string path into a FileInfo object, you can do more…

    • 15 Nov 2017
  • Power Tips: Script Logging Made Easy

    Beginning in PowerShell 5, you can use Start-Transcript in any host to log all the output created by your script. Here is how you can easily add logging capabilities to any script:

    # add this: ############################
    $logFile = "$PSScriptRoot\mylog.txt"
    Start-Transcript -Path $logFile -Append
    ($a = Get-Service)
    "I received $($a.Count) services…
    • 14 Nov 2017
  • Power Tips: Multi-Language Voice Output

    On Windows 10, the operating system ships with a bunch of high-quality text-to-speech engines and is no longer limited to just the English language. The number of available TTS Engines depends on the languages you installed.

    PowerShell can send text to these TTS Engines, and via tags can also control the language used. If you have both the English and German TTS Engines installed, you could mix languages like below:

    • 13 Nov 2017