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

    Classes (Static Members - Part 6)

    Classes can define so-called “static” members. Static members (properties and methods) can be invoked by the class itself and do not require an object instance. Let’s first see an example: #requires -Version 5.0 class TextToSpeech { # store the initialized synthesizer here hidden static $synthesizer # static constructor, gets called whenever the type is initialized static TextToSpeech (...
    • 10 Feb 2017

    Using Classes (Constructors - Part 5)

    Classes can have so-called constructors. Constructors are methods that initialize a new object. Constructors are simply methods that share the name of the class. With the help of constructors, it can be much easier to create prepopulated objects. Here is an example: the class “Person” defines a person. There is a constructor, accepting first and last name, as well as birthday.The constructor is called whenever...
    • 9 Feb 2017

    Using Classes (Overloading - Part 4)

    Methods in classes can be overloaded: you can define multiple methods with the same name but different parameters. This works similar to parameter sets in cmdlets. Have a look: #requires -Version 5.0 class StopWatch { # property is marked "hidden" because it is used internally only # it is not shown by IntelliSense hidden [ DateTime ] $LastDate = ( Get-Date ) # when no parameter is specified, do not...
    • 8 Feb 2017

    Using Classes (Adding Methods - Part 3)

    One of the great advantages of classes vs. [PSCustomObject] is their ability to also define methods (commands). Here is an example that implements a stop watch. The stop watch can be used to measure how long code takes to execute: #requires -Version 5.0 class StopWatch { # property is marked "hidden" because it is used internally only # it is not shown by IntelliSense hidden [ DateTime ] $LastDate =...
    • 7 Feb 2017

    Using Classes (Initializing Properties - Part 2)

    Class properties can be assigned a mandatory type and a default value. When you instantiate an object from a class, the properties are pre-populated and accept only the data type specified: #requires -Version 5.0 class Info { # strongly typed properties with default values [ String ] $Name = $env:USERNAME [ String ] $Computer = $env:COMPUTERNAME [ DateTime ] $Date = ( Get-Date ) } # create instance...
    • 6 Feb 2017

    Using Classes (Creating Objects - Part 1)

    Beginning in PowerShell 5, there is a new keyword called “class”. It creates new classes for you. You can use classes as a blue print for new objects. Here is code that defines the blueprint for a new class called “Info”, with a number of properties: #requires -Version 5.0 class Info { $Name $Computer $Date } # generic syntax to create a new object instance $infoObj = New-Object ...
    • 3 Feb 2017

    Using “Using Namespace”

    Working with .NET type names can be tiring because these names can be long. Here is an example: #requires -Version 2.0 Add-Type -AssemblyName System.Speech $speak = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer $speak . Speak ( ' Hello I am PowerShell! ' ) In PowerShell 5 and better, you can define the .NET namespaces you want to work with. These “using namespace” statements...
    • 2 Feb 2017

    Determining Person Age

    How do you calculate the age of a person, based on birthday? You can subtract the current time delivered by Get-Date from the birthday, but the result does not contain years: #requires -Version 1.0 $birthday = Get-Date -Date ' 1978-12-09 ' $today = Get-Date $timedifference = $today - $birthday $timedifference Here is the result: Days : 13905 Hours : 16 Minutes : 34 Seconds : 58 Milliseconds...
    • 1 Feb 2017

    Speeding Up New-Object Synthesizer

    New-Object creates new instances of objects, and you have seen one example in the past “Speech Week”: PowerShell was able to create a new speech synthesizer object, and convert text to speech: Add-Type -AssemblyName System.Speech $speak = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer $speak . Speak ( ' Hello I am PowerShell! ' ) The approach is always the same, so when you...
    • 31 Jan 2017

    Speech-Week: Using Advanced Speech Synthesizer Options Synthesizer

    The .NET speech engine accepts more than just plain text. If you use SpeakSsml() instead of Speak(), you can use XML to switch languages, speak rate, and other parameters within a text. The following example requires both an English and a German voice installed. If you don’t have a German voice installed, change the language ID in the script appropriately. Here is how you find out the language IDs available on...
    • 30 Jan 2017

    Speech-Week: Recording Voice to File Synthesizer

    The built-in Microsoft text to speech engine can save audio to a file. This way, you can auto-generate WAV files. Here is an example: it creates a new “clickme.wav” file on your desktop, and when you run the file, you hear spoken text: #requires -Version 2.0 $Path = " $home\Desktop\clickme.wav " Add-Type -AssemblyName System.Speech $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer...
    • 27 Jan 2017

    Speech-Week: Using Different Voices with Speech Synthesizer

    In the previous tip we showed how you can tap into the text to speech converter and speak out text. Here is a way to find out the installed languages on your system: #requires -Version 2.0 Add-Type -AssemblyName System.Speech $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer $speak . GetInstalledVoices () | Select-Object -ExpandProperty VoiceInfo | Select-Object -Property Culture , Name , Gender...
    • 26 Jan 2017

    Speech-Week: Using a Speech Synthesizer

    When you add the assembly “System.Speech” to PowerShell, there is a new type called “SpeechSynthesizer” which can be used to convert text to speech: Add-Type -AssemblyName System.Speech $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer $speak . Speak ( ' Hello I am PowerShell! ' ) Note that the speech synthesizer uses the default voice installed with your system. Your...
    • 25 Jan 2017

    Adding and Removing Backslashes

    For path components, it is often necessary to “normalize” paths and, for example, make sure they all end with a backslash. Some try code like this: $path = ' c:\temp ' if ( $path -notmatch ' \\$ ' ) { $path += ' \ ' } $path A regular expression is used to find a backslash at the end of some text, and if it is missing, a backslash is added. If you wanted to remove a backslash...
    • 24 Jan 2017

    Checking Number of Digits in Integer

    Sometimes you might want to check the digits of an integer, i.e. to validate user input. Here is a really simple way using regular expressions: # check the number of digits in an integer $integer = 5721567 # is it between 4 and 6 digits? $is4to6 = $integer -match ' ^\d{4,6}$ ' # is it exactly 7 digits? $is7 = $integer -match ' ^\d{7}$ ' # is it at least 4 digits? $isatleast4 = $integer ...