Blog - Post List
    • 29 Mar 2017

    Power Tips: Managing NTFS Permissions

    While there are not many built-in cmdlets to manage NTFS permissions, there is a growing list of open source PowerShell modules adding these. One promising module is written by Raimund Andree, a German Microsoft engineer who will also speak at the upcoming PowerShell Conference EU ( www.psconf.eu ). If you use PowerShell 5 or have installed PowerShellGet ( www.powershellgallery.com ), this is how you can download and...
    • 28 Mar 2017

    Power Tips: Determine if Array Contains Value – Using Wildcards

    If you’d like to know whether an array contains a given element, PowerShell provides the –contains operator. This operator does not support wildcards, though, so you only can check for exact matches. Here is a workaround that helps you filter array elements with wildcards: $a = ' Hanover ' , ' Hamburg ' , ' Vienna ' , ' Zurich ' # is the exact phrase present in array...
    • 27 Mar 2017

    Power Tips: Working with LDAP and Dates

    LDAP filters are a fast and powerful way of retrieving information from Active Directory. However, LDAP filters use a very low-level date and time format. It is basically a huge integer number. Fortunately, PowerShell contains ways of converting real DateTime objects into these numbers, and vice versa. Here is a code sample that uses Get-ADUser from ActiveDirectory module to find all users who recently changed their...
    • 24 Mar 2017

    Power Tips: Using a PowerShell Parameter Validator

    PowerShell function parameters support a ValidateScript attribute where you can assign PowerShell code. The code is invoked when the parameter receives a value from a user, and can return $true or $false. If the code returns $false, the argument is rejected. Here is a sample that accepts file names only if the file exists in the Windows folder: function Get-File { param ( [ Parameter ( Mandatory )] [ ValidateScript...
    • 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...