Blog - Post List
  • Power Tips: Real-Time Log Processing

    PowerShell comes with a powerful yet simple way of monitoring file changes. Let’s assume you have a log file that changes every now and then. This would be a PowerShell script that monitors the log file for changes, and whenever a change occurs, executes some code:

    # make sure this points to a log file
    $Path = '\\myserver\report2.txt'
    
    Get-Content -Path $Path -Tail 0 -Wait |
    ForEach-Object {
        "Detected…
    • 17 Sep 2019
  • Power Tips: Detecting Key Press

    Typically, key press detection is supported only in true console windows, so this approach won’t work for the PowerShell ISE and other PowerShell hosts.

    However, PowerShell can borrow a type from the Windows Presentation Foundation that can check the state of any key. This way, it becomes trivial to implement an “abort” key that works in any PowerShell script, whether it runs in the console, Visual Studio Code,…

    • 13 Sep 2019
  • Power Tips: Detecting Storage Issues

    In Windows 10 and Windows Server 2016, PowerShell can access storage reliability data so you can find out whether there is something wrong with one of the attached storage drives. This requires Administrator privileges to execute:

     
    PS> Get-PhysicalDisk | Get-StorageReliabilityCounter
    
    DeviceId Temperature ReadErrorsUncorrected Wear PowerOnHours
    -------- ----------- --------------------- ---- ------------
    0          …
    • 11 Sep 2019
  • Power Tips: Resetting Winsock

    PowerShell can execute internal PowerShell commands and also regular console commands, so it’s not a bad thing to continue to use console commands for proven tasks.

    For example, if you’d like to reset your winsocks, this would be a reliable solution:

    #requires -RunAsAdministrator
    
    netsh winsock reset
    netsh int ip reset
    

    Note that this code requires Administrator privileges, and may require a system restart…

    • 9 Sep 2019
  • Power Tips: Using Awesome Export-Excel Cmdlet (Part 5)

    This is part 5 of our mini-series about the awesome and free “ImportExcel” PowerShell module by Doug Finke. Make sure you install the module before you play with this tip:

     
    PS> Install-Module -Name ImportExcel -Scope CurrentUser -Force
     

    In part 4, we looked at misinterpreted data due to arrays found in the input data. As you have seen, you simply need to convert arrays to strings using the -join operator…

    • 5 Sep 2019
  • Power Tips: Using Awesome Export-Excel Cmdlet (Part 4)

    This is part 4 of our mini-series about the awesome and free “ImportExcel” PowerShell module by Doug Finke. Make sure you install the module before you play with this tip:

     
    PS> Install-Module -Name ImportExcel -Scope CurrentUser -Force
     

    In part 3, we looked at misinterpreted data due to automatic formula conversion, and examined your options to post-process individual cell formats. Let’s examine issues…

    • 3 Sep 2019
  • Power Tips: Using Awesome Export-Excel Cmdlet (Part 3)

    This is part 3 of our mini-series about the awesome and free “ImportExcel” PowerShell module by Doug Finke. Make sure you install the module before you play with this tip:

     
    PS> Install-Module -Name ImportExcel -Scope CurrentUser -Force 
     

    In part 2, we looked at misinterpreted data due to automatic number conversion. Another issue can occur when raw data “looks like” Excel formulas in which case they are…

    • 30 Aug 2019
  • Power Tips: Using Awesome Export-Excel Cmdlet (Part 2)

    This is part 2 of our mini-series about the awesome and free “ImportExcel” PowerShell module by Doug Finke. Make sure you install the module before you play with this tip:

     
    PS> Install-Module -Name ImportExcel -Scope CurrentUser -Force 
     

    When you export data to Excel files, you may sometimes encounter data that is misinterpreted by Excel. For example, often phone numbers are misinterpreted as numeric…

    • 28 Aug 2019
  • Power Tips: Using Awesome Export-Excel Cmdlet (Part 1)

    Doug Finke has created an awesome PowerShell module called ImportExcel which comes with all the commands you need to import and export data from and to Microsoft Excel. It does not require Office to be installed.

    We can’t cover all the richness this module delivers, but in this tip, we’d like to provide you with the basics to get it up and running, and in follow-up tips we’ll deal about some formatting tricks.…

    • 26 Aug 2019
  • Power Tips: Auto-Creating a List of HTTP Response Codes

    In the previous example we looked at how numeric HTTP response codes can automatically be converted to descriptive text, simply by converting them to the type System.Net.HttpStatusCode.

     
    PS> [System.Net.HttpStatusCode]500
    InternalServerError
     

    This works because System.Net.HttpStatusCode is a so-called “enumeration” and acts like a “lookup table”. You can easily dump all members of an enumeration, and for example…

    • 22 Aug 2019
  • Power Tips: Converting HTTP Response Codes

    In the previous example we created a small PowerShell function that checks web site availability, and as part of the test results, a HTTP response code was returned. Let’s check out how this numeric code can be easily converted into a meaningful text message.

    Here is the function again that tests web sites:

    function Test-Url
    {
      param
      (
        [Parameter(Mandatory,ValueFromPipeline)]
        [string]
        $Url
      )
      …
    • 20 Aug 2019
  • Power Tips: Test Web Site Availability

    When a web site is unavailable, often the question is whether it’s you, or whether the web site is generally down for everyone else, too. PowerShell can ask a web service to check web site availability for you. Here is a simple wrapper function:

    function Test-Url
    {
      param
      (
        [Parameter(Mandatory,ValueFromPipeline)]
        [string]
        $Url
      )
      
      Add-Type -AssemblyName System.Web
      
      $check = "https://isitdown…
    • 16 Aug 2019
  • Power Tips: Unit Conversion via Web Service

    Accessing RESTful web services is trivial for PowerShell: simply send your input data to a public web service, and receive the results.

    Here are three PowerShell functions designed to each do a numeric conversion:

    function Convert-InchToCentimeter
    {
      param
      (
        [Parameter(Mandatory)]
        [Double]
        $Inch
      )
      [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
      $url = 'https://ucum…
    • 14 Aug 2019
  • Power Tips: Validating Active Directory Credentials

    PowerShell can validate AD username and passwords against the Active Directory:

    Add-Type -AssemblyName System.DirectoryServices.AccountManagement
    $account = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([DirectoryServices.AccountManagement.ContextType]::Domain, $env:userdomain)
    
    $account.ValidateCredentials('user12', 'topSecret')
    

    Note that this approach is for diagnostic purposes…

    • 12 Aug 2019
  • Power Tips: Numbering Output (Part 1)

    If you’d like to add an incrementing number to your output, here is a simple way:

    Get-Process |
      Select-Object -Property '#', ProcessName, CPU -First 10 |
      ForEach-Object -begin { $i = 0} -process {
        $i++
        $_.'#' = $i
        $_
      } -end {}
    

    Select-Object adds a new property called “#”, and ForEach-Object adds an auto-incrementing number to it. The result looks similar to this:

     
    • 8 Aug 2019
  • Power Tips: Accepting Masked Passwords

    If you ever write PowerShell functions that need to accept sensitive input such as passwords, make sure you allow users to submit SecureString input. If you accept passwords via clear text, there is a substantial risk that others may see the password while being entered, or (even worse) that the password is logged and later can be found in dump files.

    Here is a simple framework that illustrates how you can achieve safe…

    • 6 Aug 2019
  • Power Tips: Finding Hidden PowerShell Applications

    The most widely known PowerShell hosts are certainly powershell.exe and powershell_ise.exe because they ship out-of-the-box. However, there can be many more (and hidden) PowerShell hosts running. Any software that instantiates the PowerShell engine is a PowerShell host. This could be Visual Studio Code (with the PowerShell extension installed), Visual Studio, or any other similar software.

    To find out all currently running…

    • 2 Aug 2019
  • Power Tips: Controlling Processor Affinity

    Most modern computers have more than one processor, either physical or logical. If you’d like to find out the number of processors, here is a chunk of PowerShell code:

    Get-WmiObject -Class Win32_Processor | 
      Select-Object -Property Caption, NumberOfLogicalProcessors
    

    The result may look similar to this:

     
    Caption                              NumberOfLogicalProcessors
    -------                              -----…
    • 31 Jul 2019
  • Power Tips: Dumping All Passwords from Chrome

    In the previous tip we illustrated how you can dump all passwords from your personal Windows Password Vault. The same is true for basically any password manager as these programs are designed to return the passwords they store for you.

    Google Chrome browsers store your personal passwords (and website history) in a SQLLite database. PowerShell can easily access this database and dump the information for you. To be able…

    • 29 Jul 2019
  • Power Tips: Dumping Personal Passwords from Windows

    Windows has a protected password vault where it can store your secret passwords so you don’t have to always enter them manually in Internet Explorer or Edge.

    If you get used to automated password managers, you may occasionally forget the original passwords. Here is a super simple PowerShell way to dump all of your passwords stored in the Windows password vault:

    # important: this is required to load the assembly…
    • 25 Jul 2019
  • Power Tips: Installing Google Chrome via PowerShell

    To download and install the Google Chrome browser, simply combine a couple of generic PowerShell commands:

    $Installer = "$env:temp\chrome_installer.exe"
    $url = 'http://dl.google.com/chrome/install/375.126/chrome_installer.exe'
    Invoke-WebRequest -Uri $url -OutFile $Installer -UseBasicParsing
    Start-Process -FilePath $Installer -Args '/silent /install' -Wait
    Remove-Item -Path $Installer
    

    Twitter This Tip! ReTweet…

    • 23 Jul 2019
  • Power Tips: Using Pop-up Dialogs that Are Always Visible

    In the previous tip we used an old COM technique to display a pop-up box with a built-in timeout. That worked pretty well except that the dialog box can be covered under your PowerShell window at times.

    With a little-known trick, you can make sure the dialog box will always open on top of all other windows:

    $shell = New-Object -ComObject WScript.Shell
    $value = $shell.Popup("You can't cover me!", 5, '…
    • 19 Jul 2019
  • Power Tips: Use Hash Tables to Make Code Readable

    Maybe you stumbled across code like this in the past:

    $shell = New-Object -ComObject WScript.Shell
    $value = $shell.Popup('Restart Computer?', 5, 'Important', 36)
    
    "Choice: $value"
    

    This chunk of code opens a dialog box and asks the user whether it is OK to restart the computer. The pop-up dialog has a built-in timeout so the code will never stall, even if running unattended.

    However, since PowerShell…

    • 17 Jul 2019
  • Power Tips: Increasing Pipeline Speed

    The PowerShell pipeline tends to be slow when it is processing a lot of elements. This can take a lot of time:

    $result = 1..15000 | 
        ForEach-Object {
            "Line $_"
        } 
    

    A much faster approach replaces ForeEach-Object with an anonymous script block and is up to 200x faster:

    $result = 1..15000 | 
        & { process {
            "Line $_"
        }}
    

    Twitter This Tip! ReTweet this Tip!

    • 15 Jul 2019
  • Power Tips: Detecting Key Presses

    It may be useful for PowerShell to know whether a given key is currently pressed. This way, your profile script could, for example, do things during PowerShell startup based on keys you hold. For example, when you hold the left CTRL key while launching PowerShell, your profile script could preload certain modules or connect you to servers.

    Here is how PowerShell detects pressed keys:

    # this could be part of your profile…
    • 11 Jul 2019