Blog - Post List
  • Power Tips: Using FileSystemWatcher Asynchronously

    In the previous tip we looked at the FileSystemWatcher object and how it can monitor folders for changes. To not miss any changes, however, an asynchronous approach is required which looks like this:

    $FileSystemWatcher = New-Object System.IO.FileSystemWatcher
    $FileSystemWatcher.Path  = "$home\Desktop"
    $FileSystemWatcher.IncludeSubdirectories = $true
    $FileSystemWatcher.EnableRaisingEvents = $true
      Register-…
    • 5 Jun 2019
  • Power Tips: Using FileSystemWatcher Synchronously

    Here is a chunk of code illustrating how PowerShell can use the FileSystemWatcher to synchronously watch a folder including subfolders for file changes:

    $folder = $home 
    $filter = '*'  
    
    
    try
    {
        $fsw = New-Object System.IO.FileSystemWatcher $folder, $filter -ErrorAction Stop
    }
    catch [System.ArgumentException]
    {
        Write-Warning "Oops: $_"
        return
    }
    
    $fsw.IncludeSubdirectories = $true
    $fsw.Not…
    • 4 Jun 2019
  • Power Tips: Using Default Credentials for Proxy

    When your company uses an authenticated proxy, PowerShell may not always be able to contact the Internet. You may have to instruct the web proxy to use your default credentials from the credential cache:

    [System.Net.WebRequest]::DefaultWebProxy.Credentials=[System.Net.CredentialCache]::DefaultCredentials
    

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

    • 3 Jun 2019
  • Power Tips: PowerShell 7

    Today we are not talking about code but about PowerShell in general. Microsoft has announced that the next release of PowerShell is called “PowerShell 7” and will be based on .NET Core 3.0. This is significant because .NET Core 3.0 re-introduces WPF (Windows Presentation Foundation, GUIs), at least on Windows machines. This way, PowerShell can re-introduce GUI-dependent cmdlets such as Out-GridView, and it is also expected…

    • 31 May 2019
  • Power Tips: RSAT Tools Built-In

    The Remote Server Administration Tools (RSAT) used to be an external download that added two important PowerShell modules: ActiveDirectory and GroupPolicy. Unfortunately, major Windows updates removed installed RSAT tools so if your scripts require Active Directory cmdlets on your client, you were forced to manually identify and download the appropriate RSAT package for your new Windows 10 and install it manually.

    This…

    • 30 May 2019
  • Power Tips: Searching Files Using Index Search

    Windows Indexing indexes most files in your user profile and drives the fast file search in File Explorer. PowerShell can access the same mechanism. Here is a function that returns files based on content:

    function Search-FileContent ([String][Parameter(Mandatory)]$FilterText, $Path = $home ) 
    { 
        $objConnection = New-Object -COM ADODB.Connection 
        $objRecordset  = New-Object -COM ADODB.Recordset 
     
        $objConn…
    • 29 May 2019
  • Power Tips: Turn on Streaming for Loops

    PowerShell comes with a number of looping constructs. These looping constructs cannot stream, so you cannot pipe the results to other cmdlets and use the pipeline real-time benefits. Instead, you must store all data in variables first, and only when the loop is completed can you pipe the variable to someone else.

    While you can resort to ForEach-Object to replace classic foreach and for loops, it slows down code and is…

    • 28 May 2019
  • Power Tips: Marking Scripts for PowerShell Core or Windows PowerShell

    As you probably know, there are two breeds of PowerShell: Windows PowerShell ships with Windows operating systems and is based on the full .NET Framework whereas PowerShell 6 and better is open-source, cross-platform, and based on the (limited) .NET Core and Standard.

    If you write scripts that run on both breeds, that’s awesome! If, however you know that your code requires either one, make sure you add the appropriate…

    • 27 May 2019
  • Power Tips: Controlling Audio Volume and Mute Status

    To adjust an audio volume and mute/unmute the speaker, PowerShell can use C# code and access API functions like this:

    Add-Type -TypeDefinition @'
    using System.Runtime.InteropServices;
    [Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IAudioEndpointVolume {
      // f(), g(), ... are unused COM method slots. Define these if you care
      int f(); int g(); int h(…
    • 24 May 2019
  • Power Tips: Checking for Bad (Insecure) Passwords (Part 2)

    In the previous tip we explained how you can use web services to safely test passwords and find out whether they have been compromised before.

    Infosec code sometimes looks pretty “funny” in an effort to be short, so in part 1 we shared nice and readable code with you. Here is the “infosec” variant which shows how much PowerShell code can be compressed and auto-obfuscated. It returns how often a particular password was…

    • 23 May 2019
  • Power Tips: Checking for Bad (Insecure) Passwords (Part 1)

    Complex passwords are not necessarily safe. For example, “P@ssw0rd” is a very complex password, however extremely insecure. That’s why security communities start to recommend that you replace complexity criteria with more relevant tests and prevent the use of passwords that have been seen in previous hacker breaches. Such passwords – however complex they may be – are a regular part of dictionary attacks and highly insecure…

    • 22 May 2019
  • Power Tips: Specifying Bit Flags Smart

    In the previous tip you have seen how you can enable all SSL security protocols in PowerShell to connect to web services and web sites:

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3 -bor [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
    

    Funny enough, a much shorter line will work just as well:

    [Net.ServicePointManager]::Secu…
    • 21 May 2019
  • Power Tips: Using SSL/HTTPS from PowerShell

    Depending on your PowerShell and .NET Framework version and update, the default security protocol for secure web connections may still be SSL3. You can easily find out:

    [Net.ServicePointManager]::SecurityProtocol
    

    If the protocol returned does not contain Tls12, you may not be able to connect to secure web services and websites using PowerShell. Simply enable more protocols like this:

    [Net.ServicePointManager]::Secur…
    • 20 May 2019
  • Power Tips: Splitting Texts by Fixed Width

    Let’s assume you need to split a text using a fixed width. For example, if you needed the first 5 character of a text, plus the remainder, how would you do this?

    Most PowerShell users would probably use string methods like these:

    $text = 'ID12:Here is the text'
    $prefix = $text.Substring(0,5)
    $suffix = $text.Substring(5)
    $prefix
    $suffix
    

    Of course, if you had a split character such as “:”, you could also…

    • 18 May 2019
  • Power Tips: Get Hashes from Texts

    Before the advent of PowerShell 5 (and Get-FileHash), to calculate hashes for strings and files, you’d need to resort to pure .NET methods. Here is sample code to create a MD5 hash for a string:

    $Text = 'this is the text that you want to convert into a hash'
    
    $Provider = New-Object -TypeName Security.Cryptography.MD5CryptoServiceProvider
    $Encodiner = New-Object -TypeName Text.UTF8Encoding
    
    $Bytes = $Enc…
    • 17 May 2019
  • Power Tips: Creating Hashes from Text

    A hash is a way to uniquely identify a text without exposing the actual text. Hashes are used to identify texts, find duplicate file content, and validate passwords. PowerShell 5 and better even comes with a cmdlet to calculate hash values for files: Get-FileHash.

    However, Get-FileHash has no way of calculating hashes from strings. Instead of saving string values to file just to calculate the hash value, you can use a…

    • 16 May 2019
  • Power Tips: Pretty Out-GridView Dialog Boxes

    When you pipe objects to Out-GridView, the cmdlet shows the default properties, so when you use a grid view window as a selection dialog, you have limited control over what the user sees. This would dump the first 10 AD users into the grid view window, and the user can select one which is returned. However, the data shown in the grid view window looks awful:

    Get-ADUser -ResultSetSize 10 -Filter * |
        Out-GridView -…
    • 14 May 2019
  • Power Tips: Redirecting PowerShell Output to GridView

    When you output data in PowerShell, it gets silently piped to Out-Default and ends up as text in the console. By overriding Out-Default, you can change this behavior and for example send all PowerShell output to a grid view window. You can in fact even separate regular output from error messages, and display both in separate windows.

    Here are two functions: Enable-GridOutput and Disable-GridOutput. When you run Enable…

    • 13 May 2019
  • Power Tips: Compare AD User

    Did you ever want to compare the properties of ADUsers? Provided you have installed the RSAT tools, you can read individual AD users with Get-ADUser, but comparing their properties isn’t easy.

    Except when you use below function: it basically splits up AD user properties into individual objects that can be compared using Compare-Object:

    #requires -Version 3.0 -Modules ActiveDirectory
    
    function Compare-User
    {
       
    • 10 May 2019
  • Power Tips: Exporting and Importing Code-Signing Certificates

    In the previous tip we explained how you can create self-signed code-signing certificates in Windows 10 and Server 2016 (and better). Today, let’s take a look at how you can export such certificates to a password protected file, and reuse the certificates on a different machine.

    Let’s assume you have created a new code-signing certificate in your personal certificate store, or there is a code-signing certificate…

    • 9 May 2019
  • Power Tips: Creating Code-Signing Certificates

    Windows 10 and Server 2016 (and better) ship with an enhanced New-SelfSignedCert cmdlet that finally can create code-signing certificates. With code-signing certificates, you can digitally sign PowerShell scripts and use the signature to detect when people tamper with your script content.

    Here is a function that you can use to create a code-signing certificate:

    function New-CodeSigningCert
    {
        param
        (
            [
    • 8 May 2019
  • Power Tips: Using Catalog Files to Maintain Folder Integrity

    If you’d like to make sure a folder content stays untouched, you can use catalog files. A catalog file lists all folder content plus creates hashes for each file in the folder. Here is an example:

    # path to folder to create a catalog file for
    # (make sure it exists and isn't too large)
    $path = "$Home\Desktop"
    # path to catalog file to be created
    $catPath = "$env:temp\myDesktop.cat"
    # create…
    • 7 May 2019
  • Power Tips: Finding PowerShell Named Pipes

    Each PowerShell host running PowerShell 5 or better opens a “named pipe” that you can detect. The code below identifies these named pipes and returns the processes exposing the pipes:

    Get-ChildItem -Path "\\.\pipe\" -Filter '*pshost*' |
    ForEach-Object {
        Get-Process -Id $_.Name.Split('.')[2]
    }
    

    The result may look similar to this:

     
    Handles  NPM(K)    PM(K)      WS(K)     CPU(s…
    • 6 May 2019
  • Power Tips: Finding the Latest PowerShell 6 Download URL

    PowerShell 6 is open-source and maintained in a public repository on GitHub. There are frequent releases. Here is a way how you can find out the download URL for the latest available PowerShell 6 release:

    $AllProtocols = [Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
    [Net.ServicePointManager]::SecurityProtocol = $AllProtocols 
    
    
    # get the URL for the latest PowerShell 6 release
    $url = "https://github.com/PowerShell…
    • 3 May 2019
  • Power Tips: Finding Latest PowerShell 6 Release (and Download URLs)

    PowerShell 6 is open-source and maintained in a public repository on GitHub. There are frequent releases.

    If you don’t want to dig your way through the GitHub front-end to find the download location for the latest PowerShell 6 release, here is a PowerShell way:

    $AllProtocols = [Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
    [Net.ServicePointManager]::SecurityProtocol = $AllProtocols 
    
    # get all releases…
    • 2 May 2019