Blog - Post List
  • Power Tips: Locking Workstation

    PowerShell can access low-level API functions by using C#-style signatures. This way, API functions are compiled in-memory and added as new types. The example below uses an API function to lock the workstation:

    Function Lock-WorkStation 
    {
        $signature = '[DllImport("user32.dll",SetLastError=true)]
        public static extern bool LockWorkStation();'
        $t = Add-Type -memberDefinition $signature -name api -na…
    • 18 Apr 2019
  • Power Tips: Command Discovery Unleashed (Part 2)

    When you enter a command in PowerShell, the engine triggers three events to actually discover the command you want to execute. This gives you a number of opportunities to intercept and change command discovery. Let’s teach PowerShell to send command output to Out-GridView whenever you add “>>” to a command name!

    Here is the code:

    $ExecutionContext.InvokeCommand.PreCommandLookupAction = {
    param
    • 17 Apr 2019
  • Power Tips: Command Discovery Unleashed (Part 1)

    Whenever you enter a command in PowerShell, a series of events takes place to figure out where the command is located. This starts with a PreCommandLookupAction which you can use to log commands. Have a look at this:

    $ExecutionContext.InvokeCommand.PreCommandLookupAction = {
    param
    (
        [string]
        $Command,
    
        [Management.Automation.CommandLookupEventArgs]
        $Obj
    )
    $whitelist = @(
    'prompt',
    'out-def…
    • 16 Apr 2019
  • Power Tips: Adding Numbers to a String (Part 2)

    In the previous tip we illustrated a number of ways how to safely add variables to string content. Adding variables to double-quoted text can expose yet another issue with automatic variable detection. Have a look:

    # this is the desired output:
    # PowerShell Version is 5.1.17763.316
    
    # this DOES NOT WORK:
    "PowerShell Version is $PSVersionTable.PSVersion"
    

    When you run this code, the output is not what most people…

    • 15 Apr 2019
  • Power Tips: Adding Numbers to a String (Part 1)

    Double-quoted strings can easily expand variables, however this concept is not foolproof:

    $id = 123
    
    # this is the desired output:
    # Number is 123:
    # this DOES NOT WORK:
    "Number is $id:"
    

    As you see in the sample above, when you place variables inside double-quoted text, PowerShell determines automatically where a variable starts and ends. A *** is considered part of the variable. To correct the issue, you need…

    • 12 Apr 2019
  • Power Tips: Get-PSCallStack and Debugging

    In the previous tip we have used Get-PSCallStack to determine the “nest level” of code. Let’s today take a look at how this cmdlet can help during debugging. To illustrate this, save the below code to a script file. It is important that it is in fact is a ps1 file. Execute it in the PowerShell ISE.

    function test1
    {
        test2
    }
    
    function test2
    {
    Wait-Debugger
    Get-Process 
        
    }
    
    test1
    

    test1 is calling…

    • 11 Apr 2019
  • Power Tips: Discovering Nesting Level

    Get-PSCallStack returns a so-called “Call Stack” which – in its simplest form – tells you the nesting depth of your code: there will be a new object added to the stack each time you enter a script block. Have a look:

    function test1
    {
        $callstack = Get-PSCallStack
        $nestLevel = $callstack.Count - 1   
        "TEST1: Nest Level: $nestLevel"    
        test2
    }
    
    function test2
    {
        $cal…
    • 10 Apr 2019
  • Power Tips: Super Simple Random Password Generator

    Here is a super simple approach to create random passwords. The approach makes sure no ambiguous characters are used but does not care about other rules such as a given minimum number of certain characters.

    $Length = 12
    $characters = 'abcdefghkmnprstuvwxyz23456789§$%&?*+#'
    $password = -join ($characters.ToCharArray() | 
    Get-Random -Count $Length) 
    
    $password 
    

    psconf.eu – PowerShell Conference EU 2019…

    • 9 Apr 2019
  • Power Tips: Preferring WLAN Connections

    When you are connected both to a LAN and a WLAN, and would like to prefer one network over the other, you can adjust the network metric. The lower the metric, the higher the network adapter preference.

    To list the current preferences, use Get-NetIPInterface. To set the metric to 10 for all WLAN adapters, for example, use a line like this:

    Get-NetIPInterface -InterfaceAlias WLAN |
      Set-NetIPInterface -InterfaceMetric
    • 8 Apr 2019
  • Power Tips: Adding Personal PowerShell Commands to the Context Menu

    You can add personal context menu commands for file types like PowerShell files. These context menu commands appear when you right-click a .ps1 file. They are specific to your account, and you don’t need admin privileges to set them up.

    Here is a script that does it for you. Just adjust the first two variables: specify the command as it should appear in the context menu, and the command to execute. In the command…

    • 5 Apr 2019
  • Power Tips: Locking the Screen with PowerShell

    Here is a PowerShell function called Lock-Screen that can lock the screen and prohibit user interaction. There can be a custom message, and the screen can be dimmed during lockout.

    Here is an example call:

     
    PS> Lock-Screen -LockSeconds 4 -DimScreen -Title 'Go away and come back in {0} seconds.'  
     

    And this is the source code to run in order to use Lock-Screen:

    Function Lock-Screen
    {
      [CmdletBinding()]
     …
    • 4 Apr 2019
  • Power Tips: Blocking User Input

    If a PowerShell script needs to perform critical steps, and user interaction must be prohibited, you can use API calls to temporarily disable all keyboard input. Locking keyboard input does require Administrator privileges.

    Here is a script illustrating how to block all keyboard input for 4 seconds:

    #requires -RunAsAdministrator
    # when run without administrator privileges, the keyboard will not be blocked!
    
    # get access…
    • 3 Apr 2019
  • Power Tips: Passing Arguments to Encoded Commands

    Encoding PowerShell code is a great way to run PowerShell code outside the PowerShell environment, i.e. in batch files. Here is some sample code that takes PowerShell code, encodes it, and shows how to run it with a console command:

    $command = {
    Get-Service | 
        Where-Object Status -eq Running | 
        Out-GridView -Title 'Pick a service that you want to stop' -PassThru | 
        Stop-Service
    }
    
    $bytes = [System…
    • 2 Apr 2019
  • Power Tips: Deleting Registry Keys that can’t be Deleted

    Deleting registry keys is typically trivial and can be done with Remove-Item. However, every once in a while, you may come across registry keys that can’t be deleted. In this tip we’ll show an example, and provide a solution.

    In the previous tip we explained that the “Run with PowerShell” context command may be missing in PowerShell files when you have defined a non-default OpenWith command, and this registry…

    • 1 Apr 2019
  • Power Tips: Repairing PowerShell Context Menus

    When you right-click a PowerShell script in File Explorer, you typically find a context menu entry called “Run with PowerShell” which lets you easily execute the PowerShell script.

    However, on some systems, the “Run with PowerShell” command is missing. It turns out the command is hidden once you define a non-default “OpenWith” command. To repair this, all you need to do is delete this registry key:…

    • 29 Mar 2019
  • Power Tips: Launching PowerShell Scripts for Dummies

    Assume you want to hand a PowerShell script to an unexperienced user. How can you reliably get that person to correctly launch your script file? Depending on the operating system and Group Policies, there might not be a context menu command to run PowerShell scripts. The user might have to fiddle with execution policy settings, too.

    Yet there is a very simple solution: ship your PowerShell script together with a shortcut…

    • 28 Mar 2019
  • Power Tips: Repairing PowerShellGet Publishing

    If you are using Publish-Module to publish your modules to a PowerShell repository, and you keep getting exceptions about unsupported commands, it might be worthwhile to reinstall the executables that manage the module upload. When these executables get too old, they may no longer be in sync with the latest PowerShellGet module.

    Run this to download and update nuget.exe with Administrator privileges (for all users):

    • 27 Mar 2019
  • Power Tips: Splitting Large Files in Smaller Parts (Part 3)

    In previous tips we illustrated how you can use PowerShell to split files into smaller file chunks, and how to join the chunks to recreate the original file. We expanded these functions even more and published them to the PowerShell Gallery, so to split and join files, just grab the module and install it like this:

     
    PS> Install-Module -Name FileSplitter -Repository PSGallery -Scope CurrentUser -Force
     

    Now whenever…

    • 26 Mar 2019
  • Power Tips: Splitting Large Files in Smaller Parts (Part 2)

    In our previous tip we explained how you can split large files into smaller chunks. Today, we complete this with a function that takes these file parts and joins them back to recreate the original file.

    Let’s consider you have split a large file into many smaller file chunks using the Split-File function that we presented in our last tip. Now you have a bunch of files with the extension “.part”. This is the result we…

    • 25 Mar 2019
  • Power Tips: Splitting Large Files in Smaller Parts (Part 1)

    PowerShell can split large files in multiple smaller parts, for example to transfer them as email attachments. Today, we focus on splitting files. In our next tip, we show how you can join the parts back together.

    To split large files into smaller parts, we created the function Split-File. It works like this:

     
    PS> Split-File -Path "C:\Users\tobwe\Downloads\Woman putting gas in Tesla.mp4" -PartSizeBytes 6MB -Verbose
    …
    • 22 Mar 2019
  • Power Tips: Sending Mails via Outlook

    To send mails via PowerShell, you can use Send-MailMessage. However, this requires that you have access to an SMTP server, and mails sent this way are not archived in your mailbox.

    To send mails via Outlook, take a look at this function:

    function Send-OutlookMail
    {
      
    param
      (
        # the email address to send to
        [Parameter(Mandatory=$true, Position=0, HelpMessage='The email address to send the mail to')]
        [Str…
    • 21 Mar 2019
  • Power Tips: Mind Jogging Generator

    The human mind can read sentences even if the characters are scrambled as long as the first and last letter of each word stays intact. Here is a PowerShell function to try out for yourself. It takes a sentence and scrambles the characters except for the first and last characters:

    function Convert-Text
    {
        param
        (
          $Text = 'Early to bed and early to rise makes a man healthy, wealthy and wise.'
        )…
    • 20 Mar 2019
  • Power Tips: Speeding Up the PowerShell Pipeline

    PowerShell scripts can grow very slow when you (a) need to process a lot of items and (b) you are using the PowerShell pipeline. Let’s today find out why that is, and what you can do about it.

    To visualize the underlying problem, let’s first create a test case that shows how PowerShell gets slowed down considerably. For this, we need a lot of items, so the code below generates a list of all files in your Windows…

    • 19 Mar 2019
  • Power Tips: Where-Object: Just A Pipeline-Aware If-Clause

    Where-Object is one of the most frequently used PowerShell commands, yet it looks unfamiliar to new PowerShell users. Those who are familiar with the “SQL” database query language can use Where-Object like the Where statement in SQL clauses: it is a client-side filter that eliminates unwanted items. This line would take all services and display only those who are actually running:

    Get-Service | Where-Obje…
    • 18 Mar 2019
  • Power Tips: Using Custom Prompts for Mandatory Parameters

    When you define mandatory parameters in PowerShell, the user gets prompted for the value if it is missing. The prompt uses the parameter name only as you can see when you run this code:

    param
    (
      [Parameter(Mandatory)]
      [string]
      $UserName
    
    )
    
    "You entered $Username"
    
     
    UserName: tobi
    You entered tobi 
     

    To get more descriptive prompts, you can use more explicit variable names:

    param
    (
      [Parameter(Mandat…
    • 15 Mar 2019