• Checking Cmdlet Availability and Script Compatibility (Part 3)

    Not all PowerShell cmdlets ship with PowerShell. Many are part of 3rd party modules which in turn ship when you install certain software, or use certain Windows versions.

    In the previous part we produced a function that dumps all external commands found in a script. With just a little extra effort, this can be turned into a useful compatibility report: any cmdlet originates from a module, and any module with a name starting…

    • 14 Mar 2019
  • Checking Cmdlet Availability and Script Compatibility (Part 2)

    Not all PowerShell cmdlets ship with PowerShell. Many are part of 3rd party modules which in turn ship when you install certain software, or use certain Windows versions.

    In the previous part we worked on a script that dumps all the external commands used by a script. We consolidated the findings with this function:

    function Get-ExternalCommand
    {
        param
        (
            [Parameter(Mandatory)][string]
            $Path
      
    • 13 Mar 2019
  • Checking Cmdlet Availability and Script Compatibility (Part 1)

    Not all PowerShell cmdlets ship with PowerShell. Many cmdlets are part of 3rd party modules which in turn ship when you install certain software, or use certain Windows versions.

    To find out the compatibility status of your scripts, in our first part we’re looking at ways to find out which commands a script actually uses. Here is a helper function that utilizes the internal PowerShell Abstract Syntax Tree (AST) to identify…

    • 12 Mar 2019
  • Colorful ASCII-Art from Images

    In the previous tip we showed you how you can take any image or photo and turn it into a black&white ASCII art. Today, we have a revised Convert-ImageToAsciiArt function for you: it takes an image and converts it to colored ASCII art!

    The pixel brightness is turned into an appropriate ASCII character, and the pixel color is applied to that character. The ASCII art is written to a HTML file since HTML is the easiest…

    • 11 Mar 2019
  • Testing Raw Data with Checksums – A Real-World Example

    With PowerShell entering the IoT world, sometimes it is necessary to deal with binary sensor data and ancient checksum models to verify data integrity.

    Here is a real-world example how PowerShell can take sensor data and validate it using a checksum. The example described here is a specific use case, however the techniques employed may well be useful for similar scenarios.

    In this example, PowerShell receives a series…

    • 8 Mar 2019
  • Inverting Bits

    Occasionally it is necessary to invert the bits for a number. Most often, this is part of custom algorithms or checksum calculations. It raises the general question: what’s the easiest way to do this?

    “Bit-Flipping” can be done with the -bnot operator like this:

    $number = 76
    [Convert]::ToString($number,2)
    
    $newnumber = -bnot $number
    [Convert]::ToString($newnumber,2)
    

    The result shows one caveat, though…

    • 7 Mar 2019
  • Calculating Most and Least Significant Byte

    Numbers are stored internally as bytes. An Int32 value, for example, uses four bytes. Sometimes it is required to split up the number into its byte parts, for example, to calculate checksums with the least significant byte.

    We have created a quick walk-through that you can also use as a basic number handling tutorial. It illustrates how numbers correspond to bits, how to split numbers to bytes, how to calculate least…

    • 6 Mar 2019
  • Accepting Parameters without Quotes

    In the previous tip, we introduced a function that generates nicely centered headers and accepted a single string. Here is the function and its results:

    function Show-Header($Text)
    {
      $Width=80
      $padLeft = [int]($width / 2) + ($text.Length / 2)
      $text.PadLeft($padLeft, "=").PadRight($Width, "=")
    }
    
     
    PS> Show-Header Starting
    ====================================Starting==========================…
    • 5 Mar 2019
  • Creating Aligned Headers

    Reporting and writing log files is a common task in PowerShell. Here is a simple function to create nicely centered headers. Adjust $width to the desired width:

    function Show-Header($Text)
    {
      $Width=80
      $padLeft = [int]($width / 2) + ($text.Length / 2)
      $text.PadLeft($padLeft, "=").PadRight($Width, "=")
    }
    

    And this is the result:

     
    PS> Show-Header Starting
    ====================================Starting…
    • 4 Mar 2019
  • Computer Name, DNS Name, and IP Address

    Here is a simple one-liner that returns your computers’ current IP address and its full DNS name:

     
    PS> [System.Net.Dns]::GetHostEntry('')
    
    HostName        Aliases AddressList                                
    --------        ------- -----------                                
    DESKTOP-7AAMJLF {}      {fe80::532:c4e:c409:b987%18, 192.168.2.129}
     

    To examine a remote machine, simply submit the computer remote…

    • 1 Mar 2019
  • Managing Windows License Key (Part 4)

    Slmgr.vbs is an ancient VBScript used to automate Windows license management. In the previous tip we started bypassing slmgr.vbs by reading the WMI directly. Aside from the SoftwareLicensingService WMI class which we already covered, there is another one called SoftwareLicensingProduct which has many instances and takes some time to retrieve:

     
    Get-WmiObject -Class SoftwareLicensingProduct | Out-GridView 
     

    The Description…

    • 28 Feb 2019
  • Managing Windows License Key (Part 3)

    Most Windows license and activation tasks can be automated using an ancient VBScript called slmgr.vbs. It does not make much sense to use this tool to get information, though, because slmgr.vbs uses localized strings and turns all data into one big string format.

    A much better way is to bypass slmgr.vbs and query the original source of information directly. To find out how slmgr.vbs does this, you can look at the script…

    • 27 Feb 2019
  • Managing Windows License Key (Part 2)

    Most automated license key management tasks are done via a command called slmgr.

    This command is actually an ancient VBScript. To read all of your license settings, for example, try this:

     
    PS> slmgr.vbs /dlv
     

    This opens a separate window, and displays many license activation details. Displaying the information in a dialog window is useless for PowerShell and automation, however when you try and run the VBScript via…

    • 26 Feb 2019
  • Managing Windows License Key

    Let’s start this mini-series with a one-liner that extracts your Windows license key:

     
    PS> $key = (Get-WmiObject -Class SoftwareLicensingService).OA3xOriginalProductKey
    
    PS> $key
    KJU8F-XXUZH-UU776-IUZGT-HHGR5  
     

    Learning points to take away:

      • WMI gets you extensive information about Windows licenses and license status.
      • One of the WMI classes used by Windows licensing is called “SoftwareLicensingService…
    • 25 Feb 2019
  • Create ASCII Art

    It’s amazing how versatile PowerShell is: with just a couple of lines of code, you can turn any photo and image into a piece of ASCII art. PowerShell simply loads the image, then scans it line by line and row by row, and replaces each pixel with an ASCII character, based on the pixel brightness.

    Here is the function:

     function Convert-ImageToAsciiArt
    {
      param(
        [Parameter(Mandatory)][String]
        $Path,
        
    • 22 Feb 2019
  • Verifying Local User Account Passwords

    In the previous tip, we asked Active Directory to validate user account passwords. The same can be done with local accounts. Your PowerShell code can use local account passwords to manage access to scripts or partial script functionality. Of course, you could also use the code below to create your own brute-force password penetration tool.

    By default, below script uses your current user name. Make sure $UserName is the…

    • 21 Feb 2019
  • Verifying Domain Account Passwords

    PowerShell can easily verify a password against a domain account. In other words, you can bind script logic to passwords maintained in Active Directory.

    Here is the code required to send a password to AD and get back a Boolean value: $true if the password is correct, else $false:

    # specify user name and user domain
    $UserDomain = $env:USERDOMAIN
    $UserName = $env:USERNAME
    $Password = Read-Host -Prompt "Enter password to…
    • 20 Feb 2019
  • Waiting for a Service Status Change

    Whenever you start or stop a service, it may take some time for the service to actually adopt the desired state – or it can of course fail. When you use Stop-Service, PowerShell waits until the desired service state is confirmed. If you want to respond to service changes initiated elsewhere, here is some monitoring code that pauses PowerShell until the desired service status is reached:

    # wait 5 seconds for spooler…
    • 19 Feb 2019
  • Converting Text to Image

    WPF (Windows Presentation Foundation)is not just a technique to create UIs. You can create any type of vector-based graphics composition and save it to a graphics file.

    Here is a simple example that takes any text and font, and renders it into a PNG file:

    function Convert-TextToImage
    {
      param
      (
        [String]
        [Parameter(Mandatory)]
        $Text,
        
        [String]
        $Font = 'Consolas',
        
        [ValidateRa…
    • 18 Feb 2019
  • Converting IEEE754 (Float) (Part 2)

    Yesterday we looked at how PowerShell can turn IEEE754 floating point values returned by a sensor into the actual value. This involved reversing the byte order and using the BitConverter class.

    If you have received a IEEE754 value in hex format, like 0x3FA8FE3B, the first task is to split the hex value into four bytes. There is a surprisingly easy way to do this: treat the hex value as an IPv4 address. These addresses…

    • 15 Feb 2019
  • Converting IEEE754 (Float) (Part 1)

    PowerShell is extremely versatile and nowadays often used with IoT and sensors as well. Some return values in IEEE754 float format which typically is a series of four hexadecimal bytes.

    Let’s assume a sensor returns a value in the hexadecimal format of 3FA8FE3B and uses IEEE754 formatting. How do you get the real value?

    Technically, you have to reverse the byte order, then use the BitConverter to produce a “Single…

    • 14 Feb 2019
  • Be Careful With “Throw” Statements (Part 2)

    In the previous tip we explained how the throw statement can be influenced by $ErrorActionPreference set to “SilentlyContinue”, and that throw will not exit function code properly. Here is again the example we used:

    function Copy-Log
    {
      "Doing prerequisites"
      "Testing whether target path exists"
      "If target path does not exist, bail out"
      throw "Target path does not exist…
    • 13 Feb 2019
  • Be Careful With “Throw” Statements (Part 1)

    Throw is a PowerShell statement that emits an exception to the caller and then exits the code. At least in theory. In the real world, throw might not exit the code, and the results can be devastating.

    To understand the problem, take a look at this demo function:

    function Copy-Log
    {
      "Doing prerequisites"
      "Testing whether target path exists"
      "If target path does not exist, bail out"
    
    • 12 Feb 2019
  • Reading News Feeds

    Here’s a special service to users with German language skills – and a challenge to adjust the code for everyone else: the code below uses the RSS feed from a major German news magazine, opens a selection window where you can select one or more articles, and then opens the selected articles in your default browser:

    # URL to RSS Feed
    $url = 'http://www.spiegel.de/schlagzeilen/index.rss'
    
    
    $xml = New…
    • 11 Feb 2019
  • Enabling Preview of PowerShell Files in Windows Explorer

    When you view PowerShell scripts in Windows Explorer and have the preview pane open, by default you don’t get a code preview for your script files. The preview pane remains blank.

    To enable the preview, simply use the function below:

    function Enable-PowerShellFilePreview
    {
        [CmdletBinding()]
        param
        (
            [string]
            $Font = 'Courier New',
            
            [int]
            $FontSize = 60
    
    • 8 Feb 2019