• Displaying Message Box

    If you’d like to show a default MessageBox with some buttons for the user to click, try this function:

    function Show-MessageBox
    {
      [CmdletBinding()]
      param
      (
        [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
        [String]
        $Text,
        
        [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
        [String]
        $Caption,
        
        [Parameter(Mandatory=$true,ValueFromPipeline=$false)]
        [Windows.Mess…
    • 20 Jun 2018
  • Displaying Input Box

    If you’d like to open a quick and dirty input box to prompt a user for some data, you could access Microsoft Visual Basic and “borrow” its InputBox:

    Add-Type -AssemblyName Microsoft.VisualBasic
    $result = [Microsoft.VisualBasic.Interaction]::InputBox("Enter your Name", "Name", $env:username)
    $result
    

    Note though that this approach has some limitations: the input box may open behind…

    • 19 Jun 2018
  • Reading Text Files Fast

    There are plenty of ways how PowerShell can read in text files, and they can differ considerably in time. Check for yourself. The examples below illustrate different approaches and measure the execution times. Just make sure the path in the example exists, and if not, choose a large text file to play with.

    # make sure this file exists, or else
    # pick a different text file that is
    # very large
    $path = 'C:\Windows\Logs…
    • 18 Jun 2018
  • Create Universal Time from Local Time in ISO Format

    If you’re working across countries and time zones, you may want to use universal time instead of local time. And to ensure that the time format is culture neutral, using the ISO format is recommended. Here is how:

    $date = Get-Date
    $date.ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')
    

    Twitter This Tip! ReTweet this Tip!

    • 15 Jun 2018
  • Reading Event Logs Smart (Part 2)

    In the previous tip we illustrated how you can access detailed event log information that you retrieved via Get-EventLog by using ReplacementStrings. That worked beautifully, however Get-EventLog can only read the “classic” Windows logs. There are hundreds of additional logs in modern Windows versions.

    These logs can be read via Get-WinEvent, and there is a wealth of information to discover. For example, to…

    • 14 Jun 2018
  • Reading Event Logs Smart (Part 1)

    When you query an event log with PowerShell, by default you get back a text message with the logged information. For example, if you’d like to know who logged on to your machine, you could use code like this (Administrator privileges required):

    Get-EventLog -LogName Security -InstanceId 4624 |
      Select-Object -Property TimeGenerated, Message
    

    The result could look like this:

     
    ...
    25.04.2018 07:48:41 An account…
    • 13 Jun 2018
  • Understanding Type Accelerators (Part 2)

    PowerShell comes with a number of hard-coded type accelerators that serve like aliases for commonly used .NET types, and since they are a lot shorter than the original type names, they “accelerate the typing”.

    A little-known fact is that the list of type accelerators is extensible. The line below adds a new type accelerator named “SuperArray” that points to “System.Collections.ArrayList”…

    • 12 Jun 2018
  • Understanding Type Accelerators (Part 1)

    “Type Accelerators” work like aliases for .NET types. They are intended to save typing. For example, the [ADSI] “type” really does not exist. It is a mere alias for System.DirectoryServices.DirectoryEntry. You could replace [ADSI] by [System.DirectoryServices.DirectoryEntry]:

     
    PS> [ADSI].FullName
    System.DirectoryServices.DirectoryEntry 
    
    
    PS> [System.DirectoryServices.DirectoryEntry].FullName…
    • 11 Jun 2018
  • Out-Notepad: Send Information to Notepad

    Have you ever wanted to send text directly to Notepad, without having to use a file?

    Typically, you would need to write the text to a file, then open Notepad and instruct it to load the file. There is also a more exotic way: communicate with Notepad via Windows messages, and beam text right into Notepad. This is what Out-Notepad does:

    #requires -Version 2
    function Out-Notepad
    {
      param
      (
        [Parameter(Mandatory=$t…
    • 8 Jun 2018
  • Using Secret $FormatEnumerationLimit variable

    Format-List by default displays object properties in a list, and if a property contains an array, the array is turned into text, and only a few array elements are displayed. Here is an example:

     
    PS> Get-Process -Id $Pid | Format-List -Property Name, Modules
    
    
    Name    : powershell_ise
    Modules : {System.Diagnostics.ProcessModule (PowerShell_ISE.exe), 
              System.Diagnostics.ProcessModule (ntdll.dll), System.Diagnostics…
    • 7 Jun 2018
  • Turning Display Off Immediately

    If you are about to launch a lengthy automation script, why not turn off the display right away instead of waiting for the screen saver timeout to kick in?

    Here is a simple function that turns off your display immediately. Just move the mouse or press a key to turn it back on:

    function Set-DisplayOff
    {
        $code = @"
    using System;
    using System.Runtime.InteropServices;
    public class API
    {
      [DllImport("user32.dll")]
      public…
    • 6 Jun 2018
  • Configuring Network Adapter

    Here is a simple example illustrating how you assign IP address, gateway, and DNS server to a network adapter. The script lists all active network adapters, and when you select one and click OK, uses the hard-coded addresses to assign new values.

    Note that the script below only pretends to do the changes. Remove the -WhatIf parameter to actually assign new values:

    $NewIP = '192.168.2.12'
    $NewGateway = '192…
    • 5 Jun 2018
  • Free PowerShell Help Manuals

    Even experienced PowerShell users often ignore that PowerShell comes with an excellent help system, much similar to the man pages in Linux. All you need to do is download the help files once. For this, you need to run the line below in a PowerShell with elevated privileges:

     
    PS> Update-Help -UICulture en-us -Force
     

    Once the help files are downloaded, here’s the list of awesome background topics that explain almost…

    • 4 Jun 2018
  • Managing Windows 10 Default Apps with PowerShell

    Windows 10 comes with a load of apps preinstalled, and even if you remove things manually, they might come back after the next big Windows 10 update.

    PowerShell can remove these Windows 10 apps as well, and you can re-run the script anytime you want to ensure that cleaned up apps are indeed removed. This line for example removes the 3D Builder App:

     
    PS> Get-AppxPackage *3dbuilder* | Remove-AppxPackage
     

    There is a…

    • 1 Jun 2018
  • Using Magic Script Block Parameters

    In the previous example we showed the special nature of the -NewName parameter in Rename-Item. it accepts a new file name, but also a script block that can be used to bulk-rename many files.

    Let’s now take a look at how PowerShell functions can implement such magic parameters! Here is a function that defines two parameters:

    function Test-MagicFunc
    {
      [CmdletBinding()]
      param
      (
    
        [Parameter(Mandatory=$tru…
    • 31 May 2018
  • Bulk-Renaming Pictures

    Renaming a single file is easy using Rename-Item, but sometimes cmdlet parameter can be much smarter and help you automate in bulk.

    For example, let’s assume you have a load of pictures in your picture folder:

    $path = [Environment]::GetFolderPath('MyPictures')
    Get-ChildItem -Path $path -Filter *.png
    

    If you wanted to rename all of them, i.e. by prepending a number, you would have to program a loop, like…

    • 30 May 2018
  • PowerShell Gallery dbatools – PowerShell Extension for Database Professionals

    In the previous tip we explained how you can get PowerShellGet up and running with your PowerShell version. Now let’s see how easily the PowerShell Gallery can extend the PowerShell functionality.

    PowerShell is a general-purpose automation language, and database professionals from around the world have started to work on a PowerShell extension called “dbatools” that can be freely downloaded from the PowerShell gallery…

    • 29 May 2018
  • PowerShell Gallery: Discovering Script Block Logging (Part 2)

    In the previous tip we introduced the free ScriptBlockLoggingAnalyzer module which uncovers the code that PowerShell logs. By default, this is limited to only a few commands, but if you enable full Script Block Logging, then any code run by anyone on your machine is logged.

    Here are the steps to take (applies to Windows PowerShell, run from a PowerShell with elevated privileges!):

    #requires -RunAsAdministrator
    
    # install…
    • 28 May 2018
  • PowerShell Gallery: Discovering Script Block Logging (Part 1)

    In the previous tip we explained how you can get PowerShellGet up and running with your PowerShell version. Now let’s see how easily the PowerShell Gallery can extend the PowerShell functionality.

    ScriptBlock Logging is a new feature in PowerShell 5 and beyond. Whenever the PowerShell engine compiles (executes) a command, it logs it to an internal log file. By default, only a few commands are logged that are considered…

    • 25 May 2018
  • PowerShell Gallery: Creating QR GeoLocations

    In the previous tip we explained how you can get PowerShellGet up and running with your PowerShell version. Now let’s see how easily the PowerShell Gallery can extend the PowerShell functionality.

    Next time you send an invitation for a meeting, class, or party, why not add a geolocation QR code? Most modern smart devices can scan such codes via their camera app, and show the location in a map, and provide directions…

    • 24 May 2018
  • PowerShell Gallery: Creating QRCode vCards

    In the previous tip we explained how you can get PowerShellGet up and running with your PowerShell version. Now let’s see how easily the PowerShell Gallery can extend the PowerShell functionality.

    Next time you print business cards, why not add a QR code? It makes adding contacts so much easier! Most modern smart devices support QR codes, and when you point the camera app to a QR code, the smart phone offers to…

    • 23 May 2018
  • PowerShell Gallery: Creating QR Codes

    In the previous tip we explained how you can get PowerShellGet up and running with your PowerShell version. Now let’s see how easily the PowerShell Gallery can extend the PowerShell functionality.

    To create a QR code for WiFi access, you just need a few lines of code now:

    # adjust this to match your own WiFi
    $wifi = "myAccessPoint"
    $pwd = "topSecret12"
    
    
    # QR Code will be saved here
    $path = 
    • 22 May 2018
  • Accessing Free PowerShell Gallery (Part 2)

    PowerShellGet is a new free extension for PowerShell that enables you to download and install free extensions and commands. It comes with PowerShell 5, and in the previous tip we explained how you can update it to the latest version.

    If you are using an older PowerShell version, the best advice is to update PowerShell. If you can’t do this, you can install the PowerShellGet module via a free MSI package here: https…

    • 21 May 2018
  • Accessing Free PowerShell Gallery (Part 1)

    PowerShell is an extensible framework, and there are tons of free and very useful command extensions available on the PowerShell Gallery (www.powershellgallery.com). We’ll be examining the vast power of this gallery in a couple of tip posts.

    To download and install any extension from PowerShellGallery, you need the PowerShellGet module which provides you with the commands to browse, download, install, update, and…

    • 18 May 2018
  • Printing Tables from PowerShell (using WPF)

    Whenever you would like to display, print, or save as PDF in a tabular form, WPF (Windows Presentation Foundation) may be a good way. Originally, WPF was created to define user interfaces, but you can as well use it to define tables, fill in the data, and print or save them.

    Don’t be put off by the amount of code. PowerShell is basically defining the table in an object-oriented way.

    The example code below creates…

    • 17 May 2018