Blog - Post List
    • 23 Mar 2017

    Power Tips: Casting Data with Culture

    When casting data (converting it to a different data type), PowerShell supports two approaches that can differ considerably. Here is an example: [ DateTime ] ' 12.1.2017 ' ' 12.1.2017 ' -as [ DateTime ] Both lines cast a string into a DateTime object. The first line represents a forceful cast. It will either succeed or fail, and it always uses culture-neutral format (US format), so it expects...
    • 22 Mar 2017

    Power Tips: Invoking a Script Block

    Code inside a script block can either be invoked by call operators such as „&“ or „.“, or by calling the Invoke() method. One difference is the output when there is more than one result: call operators return a plain object array whereas Invoke() returns a collection: $code = { Get-Process } $result1 = & $code $result2 = $code . Invoke () $result1 . GetType () . FullName $result2...
    • 21 Mar 2017

    Power Tips: Running Cmdlets without Verb

    This has been part of PowerShell since version 1.0: cmdlets with verb „get“ can be invoked without the verb. So instead of „Get-Service“, you can run „Service“, and instead of „Get-Date“, you can run „Date“. These are no aliases, and apparently even the PowerShell engine does not know why this works. Try running these: PS > Date PS > Get-Command Date...
    • 20 Mar 2017

    Power Tips: Texts with Maximum Length (Part 2)

    Here is another strategy to make sure a text does not exceed a given length. In contrast to our previous tip, this code will not pad spaces in case the text is shorter than the maximum length: $text = ' this ' $MaxLength = 10 $CutOff = [ Math ] :: Min ( $MaxLength , $text . Length ) $text . Substring ( 0 , $CutOff ) Key is the Min() method which determines the smaller of two values. ReTweet this Tip...
    • 17 Mar 2017

    Power Tips: Texts with Maximum Length (Part 1)

    If you want to make sure a text is of given length, here is an easy approach: $text = ' this is a long text ' $MaxLength = 10 $text . PadRight ( $MaxLength ) . Substring ( 0 , $MaxLength ) This code first pads the text in case it is shorter than the maximum length, and then Substring() is cutting off excess text. ReTweet this Tip!
    • 16 Mar 2017

    Power Tips: Finding All Profiles with Desktop

    This simple line dumps all paths to all desktops found in any of the local user profiles – just make sure you are running the line with Administrator privileges to see other peoples‘ profiles: Resolve-Path -Path C :\ users \ * \ Desktop -ErrorAction SilentlyContinue If you just would like to get the user names for those profiles that have a „Desktop“ folder, try this: Resolve-Path -Path...
    • 15 Mar 2017

    Power Tips: Where-Object and .Where()

    Beginning in PowerShell 4, you can use the Where() and Foreach() methods in place of Where-Object and ForEach-Object whenever you do not want to use the streaming mechanism of the pipeline. So if you already loaded all data into a variable, the non-streaming mechanism can be faster: $Services = Get-Service # streaming $Services | Where-Object { $_ . Status -eq ' Running ' } # non-streaming $Services...
    • 14 Mar 2017

    Power Tips: Creating Object Arrays on the Fly

    Here is a quick code sample that generates an array of objects using the built-in CSV parser: $csv = @' PC , Date PC82012 , 2017 - 02 - 28 PC82038 , 2017 - 02 - 28 PC83073 , 2017 - 02 - 28 PC84004 , 2017 - 02 - 28 PC84009 , 2017 - 02 - 28 PC84015 , 2017 - 02 - 28 PC90435 , 2017 - 02 - 28 '@ $data = $csv | ConvertFrom-Csv $data $data | Out-GridView This can be useful if a script...
    • 13 Mar 2017

    Power Tips: Exploring Type Accelerators

    PowerShell uses a number of so-called type accelerators that help with long .NET type names. Instead of using “System.DirectoryServices.DirectoryEntry”, for example, you can simply type “ADSI”. When you query the property FullName of a type, you always get back the underlying full .NET type name: PS C:\> [ADSI].FullName System.DirectoryServices.DirectoryEntry PS C:\> And this line...
    • 10 Mar 2017

    Power Tips: Dangerous Temp Files!

    Internal system functions are often helpful, but always make sure you fully understand what they do. A particularly popular system method is called GetTempFileName() and produces temporary file names. When you look a bit closer, though, you’ll notice that it not just produces temporary file names, but also temporary files: $file = [ System.IO.Path ] :: GetTempFileName () Test-Path -Path $file So you’ll...
    • 9 Mar 2017

    Power Tips: Explore Objects

    In PowerShell, anything is represented by objects, and here is a helpful one-liner that examines any object and copies its members as text into your clipboard. "Hello" | Get-Member | Format-Table -AutoSize -Wrap | Out-String -Width 150 | clip.exe Simply replace “Hello” with any variable or command, and see what is copied to your clipboard. You can then paste the information to the text...
    • 8 Mar 2017

    Power Tips: Managing Bit Flags (Part 4)

    In PowerShell 5, the new support for enums makes dealing with bit values much easier as you’ve seen in previous tips. Even setting or clearing bits no longer requires cumbersome logical operators anymore. Let’s first define an enum and make the decimal more manageable: #requires -Version 5 [ Flags ()] enum GardenPartyItems { Chair = 0 Table = 1 Barbecue = 2 Fridge = 4 Candle = 8 Knife =...
    • 7 Mar 2017

    Power Tips: Managing Bit Flags (Part 3)

    Setting or clearing bit flags in a decimal is not particular hard but unintuitive. Here is a quick refresher showing how you can set and clear individual bits in a number: $decimal = 6254 [ Convert ] :: ToString ( $decimal , 2 ) # set bit 4 $bit = 4 $decimal = $decimal -bor [ Math ] :: Pow ( 2 , $bit ) [ Convert ] :: ToString ( $decimal , 2 ) # set bit 0 $bit = 0 $decimal = $decimal -bor [ Math ] :: Pow ...
    • 6 Mar 2017

    Power Tips: Managing Bit Flags (Part 2)

    In the previous tip we illustrated how you can use PowerShell 5’s new enums to easily decipher bit flags, and even test for individual flags. If you cannot use PowerShell 5, in older PowerShell versions, you can still use this technique. Simply define the enum via C# code: # this is the decimal we want to decipher $rawflags = 56823 # define an enum with the friendly names for the flags # don't forget...
    • 3 Mar 2017

    Power Tips: Managing Bit Flags (Part 1)

    Occasionally, you might have to deal with bit flag values. Each bit in a number represents a certain setting, and your code might need to determine whether a given flag is set, or set a given flag without tampering with the other bits. This typically involves a lot of fiddling with binary operators. In PowerShell 5, however, there is a much easier approach, thanks to the support for flag enumerations. Let’s...
    • 2 Mar 2017

    Power Tips: Working With Generics

    Generic types can use placeholders for actual types, and you may be wondering why that can be exciting. There are a number of data types, for example, that have no NULL value. Integers for example, and also Boolean values, have no way of signaling that a value is invalid or not set. You can work around this by defining that an integer with 0 (or -1) should be an “undefined” value. But what if all numbers...
    • 1 Mar 2017

    Power Tips: Inheriting Classes in PowerShell 5 (part 2)

    Here is another use case for the new class feature in PowerShell 5. In the previous example, we illustrated how you can derive new classes from System.Diagnostics.Process to get new and more powerful objects representing running processes. Here’s a class that inherits from WebClient which is typically used to connect to websites. When you use the regular WebClient object, it refuses to connect to HTTPS sites with...
    • 28 Feb 2017

    Power Tips: Inheriting Classes in PowerShell 5 (part 1)

    PowerShell 5 comes with built-in support for classes. You can use this new feature to enhance existing .NET classes. Here is an example: let’s create an enhanced process class with additional functionality. Processes are typically represented by System.Diagnostics.Process objects. They have limited functionality, and for example provide no out-of-the-box way of gracefully closing an application. You can either...
    • 27 Feb 2017

    Power Tips: Show or Hide Windows

    PowerShell can call internal Windows API functions, and in this example, we’d like to show how you can change the show state of an application window. You’ll be able to maximize, minimize, hide, or show, for example. The example uses PowerShell 5’s new enum capability to give the showstate numbers meaningful names. In older versions of PowerShell, simply remove the enum, and use the appropriate showstate...
    • 24 Feb 2017

    Power Tips: Using Pester Tests to Test Anything

    Pester is an open source module shipping with Windows 10 and Windows Server 2016, and can be downloaded from the PowerShell Gallery (www.powershellgallery.com) for free (provided you have installed at least PowerShellGet): PS C:\> Install-Module -Name Pester -Force -SkipPublisherCheck Pester is a testing framework primarily used to test PowerShell code. You are not limited to code tests, though, and so you...
    • 23 Feb 2017

    Power Tips: Reading Environment Variables Freshly

    When you read environment variables in PowerShell, you probably make use of the “env:” drive. This line retrieves the environment variable %USERNAME%, for example, telling you the name of the user executing the script: PS C:\> $env:USERNAME tobwe PS C:\> The “env:” drive always accesses the process set of environment variables. This makes sense in most cases as many of the environment...
    • 22 Feb 2017

    Power Tips: Setting Environment Variables

    When setting environment variables through the PowerShell “env:” drive, you are always just manipulating the process set. It applies to your current PowerShell instance, and all applications that you start from there. Changes will not persist, though. To permanently set an environment variable, use this code instead: $name = ' Test ' $value = ' hello ' $scope = [ EnvironmentVariableTarget...
    • 21 Feb 2017

    Power Tips: Checking Host

    In the past, Microsoft shipped two PowerShell hosts: the basic PowerShell console, and the more sophisticated PowerShell ISE. Some users used code like below to find out whether a script runs in the console or the PowerShell ISE: $inISE = $psISE -ne $null "Running in ISE: $inISE" However, there are many more hosts around these days. Visual Studio can host PowerShell, and so does Visual Studio Code....
    • 20 Feb 2017

    Power Tips: Playing with PowerShell 6.0

    PowerShell is open source now, and the next big release of PowerShell is being developed in the open. If you’d like to take a peek preview, simply navigate to the open source project release page, and download the appropriate release: https://github.com/PowerShell/PowerShell/releases PowerShell 6.0 is also a cross-platform. You find versions for Windows operating systems right next to versions for Linux or OS...
    • 17 Feb 2017

    Power Tips: Caching Credentials Using JSON

    When you need to cache logon credentials to a file, this is typically done by piping the credential to Export-Clixml which produces a rather lengthy XML file. With Import-Clixml, the cached credential can then be imported back into a script whenever you need it. PowerShell automatically uses the user and machine identity to encrypt the password (and it can only be read back by the same person on the same machine). The...