• 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
  • Removing Empty Array Elements (Part 2)

    If you want to eliminate completely empty array elements (and do not need to focus on empty properties), here are some approaches with fundamentally different performance:

    # create huge array with empty elements
    $array = 1,2,3,$null,5,0,3,1,$null,'',3,0,1
    $array = $array * 1000
    
    # "traditional" approach (6 sec)
    Measure-Command {
        $newArray2 = $array | Where-Object { ![string]::IsNullOrWhiteSpace(
    • 7 Feb 2019
  • Removing Empty Array Elements (Part 1)

    Occasionally you come across lists (arrays) with empty elements. What’s the best way of removing empty elements?

    Let’s first focus on a common use case: the code below creates a software inventory by reading the installed software from the registry. The software list is then displayed in a grid view window, and most likely you’ll see elements with empty properties:

    $Paths = 'HKCU:\Software\Microsoft…
    • 6 Feb 2019
  • “Dangerous” Comparisons

    Let’s assume in an array you want to get rid of all elements that are either empty or null. This is what many would do:

     
    PS> 1,2,$null,"test","",9 | Where-Object { $_ -ne '' -and $_ -ne $null }
    
    1
    2
    test
    9
    
    PS>  
     

    However, this comparison is dangerous because it also eliminates the value 0:

     
    PS> 1,2,0,$null,"test","",0,9 | Where-Object { $_ -ne '' -and $_ -ne $null }
    
    1
    2
    test…
    • 5 Feb 2019
  • Calculating First and Last Day of Month

    For reporting and similar use cases, scripts may require the first and last day in a given month. The first day is easy, yet the last day depends on month and year. Here is a simple calculator. Just specify the month and year you need:

    [ValidateRange(1,12)][int]$month = 3
    $year = 2019
    $last = [DateTime]::DaysInMonth($year, $month)
    $first = Get-Date -Day 1 -Month $month -Year $year -Hour 0 -Minute 0 -Second 0
    $last = 
    • 4 Feb 2019
  • Formatting a DateTime

    Whenever you have a true DateTime (and not a string, for example), you have plenty of powerful ways to format. You can get DateTime objects directly:

     
    PS> $installDate = (Get-CimInstance -Class Win32_OperatingSystem).InstallDate
    
    PS> $installDate.GetType().FullName
    System.DateTime 
     

    Or you can convert a string to a DateTime:

     
    PS> $psconf = Get-Date -Date '2019-06-04 09:00'
    
    PS> $psconf.GetType().FullName
    System…
    • 1 Feb 2019
  • Extracting Windows Installation Date

    Ever wondered how old your Windows installation is? A one-liner can tell:

     
    PS> (Get-CimInstance -Class Win32_OperatingSystem).InstallDate
    
    Freitag, 8. Juni 2018 18:24:46  
     

    Two things are noteworthy: first, we are apparently using a German system. Second, the install date may be much more recent than you think: every new major Windows 10 update actually performs a full reinstall.

    If you’d like to change the culture…

    • 31 Jan 2019
  • Hide OneDrive from File Explorer

    Are you tired of OneDrive icons polluting your file explorer tree view? If you don’t use OneDrive, then here are two handy functions that hide and show the OneDrive icons in File Explorer:

    function Disable-OneDrive
    {
      $regkey1 = 'Registry::HKEY_CLASSES_ROOT\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}'
      $regkey2 = 'Registry::HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6…
    • 30 Jan 2019
  • Turn a Windows Server into a Workstation

    PowerShell 5 and later releases come with a cmdlet to automatically add new Windows features, so if you are running a Windows Server and would like to use the Workstation features on it, open a PowerShell with Administrator privileges, and run this line:

    Enable-WindowsOptionalFeature -FeatureName DesktopExperience -All -Online -NoRestart 
    

    psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit…

    • 29 Jan 2019
  • Automatically Printing to XPS Files

    XPS is a document format similar to PDF from Microsoft. Although it never really was used in a large scale, it can still be a valuable internal format to print information to a file. To print unattended to XPS files, first you need to set up a new printer that automatically prints to a specific output file:

    #requires -RunAsAdministrator
    
    $OutPath = "$env:temp\out.xps"
    $PrinterName = "XPSPrinter"
    Add…
    • 28 Jan 2019
  • Removing BOM from the Unicode Files

    BOM (Byte Order Mask) is a characteristic byte sequence used in some Unicode encoded text files. If you receive text files with BOM that need to be processed by systems not supporting BOM, here is a way how PowerShell can remove the BOM from such files:

    function Remove-BomFromFile ($OldPath, $NewPath)
    {
      $Content = Get-Content $OldPath -Raw
      $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
      [IO.File
    • 25 Jan 2019
  • PowerShell Cheat Sheet Compilation (Part 2)

    In the previous tip we pointed you to a great compilation of PowerShell cheat sheets. Let’s now check out how easily PowerShell can download these sheets for you:

    # enable SSL download
    $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
    [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
    
    # download page
    $url = "https://github.com/PrateekKumarSingh/CheatSheets/tree/master…
    • 24 Jan 2019
  • PowerShell Cheat Sheet Compilation (Part 1)

    Here is a great compilation of popular PowerShell cheat sheets, completely free and ready for download:

    https://github.com/PrateekKumarSingh/CheatSheets/tree/master/Powershell

    psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one…

    • 23 Jan 2019
  • Get Text File Encoding

    Text files can be stored using different encodings, and to correctly reading them, you must specify the encoding. That’s why most cmdlets dealing with text file reading offer the -Encoding parameter (for example, Get-Content). If you don’t specify the correct encoding, you are likely ending up with messed up special characters and umlauts.

    Yet how do you (automatically) determine the encoding a given text…

    • 22 Jan 2019
  • Controlling PowerShell Transparency with Mouse Wheel

    On Windows 10, when you hold CTRL+SHIFT and then move your mouse wheel, you can easily control the transparency of console window, including the PowerShell console window.

    psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place…

    • 21 Jan 2019
  • Retrieving Windows Product Key

    Here is a one-liner that retrieves your original Windows product key:

    (Get-WmiObject -Class "SoftwareLicensingService").OA3xOriginalProductKey
    

    psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want…

    • 18 Jan 2019
  • Printing PDF Files (Part 2)

    In the previous tip we explained how PowerShell can send PDF documents to the default PDF printer. This generic approach is OK for simple scenarios but won’t let you choose a specific printer.

    You get more control when you use a specific software because then you can use specific features exposed by that software.

    The example below uses Acrobat Reader to print out PDF documents. It shows how you can use the specific…

    • 17 Jan 2019
  • Printing PDF Files (Part 1)

    To automatically print PDF documents, unfortunately you cannot use Out-Printer. Out-Printer can only send pure text documents to a printer.

    However, take a look at this line:

    # adjust this path to the PDF document of choice
    $Path = "c:\docs\document.pdf"
    
    Start-Process -FilePath $Path -Verb Print
    

    Provided you have software installed that can print PDF document, this code sends the document to the associated…

    • 16 Jan 2019
  • Installing Linux on Windows 10

    Windows 10 comes with Windows Subsystem for Linux (WSL) feature that you can use to run various Linux distributions. Launch a PowerShell with elevated privileges to enable the WSL:

    Enable-WindowsOptionalFeature -FeatureName Microsoft-Windows-Subsystem-Linux -Online  
    

    Next, open the Microsoft Store on Windows 10, and search for “Linux”. Install one of the supported Linux distros (for example, Debian)!

    That…

    • 15 Jan 2019
  • Using Localized User and Group Names

    Here is a one-liner that returns the resolved name from the current user’s SID:

    ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Translate( [System.Security.Principal.NTAccount]).Value
    

    You may be arguing it is easier to query the environment variable $env:username for this, which is true. However, converting a SID to name can come handy in many scenarios. For example, if you must know the exact…

    • 14 Jan 2019