• 20 Mar 2017

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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...
    • 16 Feb 2017

    Free Guides to Start With PowerShell

    If you have colleagues that don’t know PowerShell, and you would like them to get started, here are three free learning resources: https://go.veeam.com/powershell-study-guide https://www.manning.com/books/exploring-powershell-automation http://community.idera.com/powershell/powertips/b/ebookv2#pi619PostSortOrder=Ascending ReTweet this Tip!
    • 15 Feb 2017

    Identifying Problematic Execution Policy Settings

    PowerShell uses execution policy to determine which scripts to run. There are in fact five scopes where execution policy can be defined, and to see them all, use this command: PS C:\> Get-ExecutionPolicy -List Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser RemoteSigned LocalMachine Undefined To determine the effective setting, PowerShell...
    • 14 Feb 2017

    Checking Execution Policy

    Execution policy determines what kind of scripts PowerShell will execute. You need to set execution policy to something other than Undefined, Restricted, or Default in order for scripts to run. For inexperienced users, the “RemoteSigned” setting is recommended. It runs local scripts, and scripts located on fileservers inside your trusted network domain. It won’t run scripts downloaded from the internet...