Blog - Post List
  • Power Tips: Hardening PowerShell Script Block Logging Log

    When you enable ScriptBlockLogging, PowerShell logs all PowerShell code that is executed on your machine. Even if it is disabled, any security-relevant code is still logged. That’s awesome. However, the log can be read by any user, so anyone could browse through the logged code like this:

    Get-WinEvent -FilterHashtable @{ ProviderName="Microsoft-Windows-PowerShell";  Id = 4104 } 
    

    To harden security and…

    • 17 Aug 2018
  • Power Tips: Manipulating Registry User Hive

    Reading and writing values to the HKEY_LOCAL_USER hive in the registry is easy, because this hive is the same for all users. How would you read or write values the HKEY_CURRENT_USER hive for a user that is not you?

    Let’s assume you are admin and want to add registry values to the HKEY_CURRENT_USER hive of another user.

    First you need to mount the user hive of that person. That hive is located in the NTUSER.DAT file…

    • 16 Aug 2018
  • Power Tips: Managing Windows Features (Part 2)

    In Windows 10, unlike in Windows Server, you cannot use the Get-WindowsFeature and Add-WindowsFeature cmdlets to manage Windows features.

    However, for clients there is a very similar cmdlet available: Enable-WindowsOptionalFeature. These lines would add the PowerShell Hyper-V cmdlets and the Hyper-V features:

    Enable-WindowsOptionalFeature -Online -All -FeatureName Microsoft-Hyper-V-Management-PowerShell -NoRestart
    Enable…
    • 15 Aug 2018
  • Power Tips: Managing Windows Features (Part 1)

    Windows 10 comes with a vast number of features, and only a subset is installed. Manually, you would open Control Panel and look at the Windows Feature list. Experienced Administrators may also use the dism.exe command-line tool.

    With PowerShell, you can view the state of Windows features via Get-WindowsOptionalFeature. When you specify –Online, the cmdlet returns the currently available features and their states.…

    • 14 Aug 2018
  • Power Tips: Running CMD commands in PowerShell

    PowerShell by default does not support the native cmd.exe command such as „dir“. Instead, it uses historic aliases called “dir” to point you to the closest PowerShell cmdlet:

     
    
    PS C:\> Get-Command -Name dir | ft -AutoSize
    
    CommandType Name                 Version Source
    ----------- ----                 ------- ------
    Alias       dir -> Get-ChildItem 
     

    This explains why “dir” in PowerShell…

    • 13 Aug 2018
  • Power Tips: Getting Excuses Automatically

    Invoke-WebRequest can retrieve HTML info from web pages, and regular expressions can then scrape information from these pages.

    Here is some code that gets you excuses in English:

    $ProgressPreference = 'SilentlyContinue'
    
    $url = "http://pages.cs.wisc.edu/~ballard/bofh/bofhserver.pl?$(Get-Random)"
    $page = Invoke-WebRequest -Uri $url -UseBasicParsing
    $pattern = '(?s)<br><font\ size\ =\ "\+2">(.{1,}…
    • 10 Aug 2018
  • Power Tips: Separating Variables in Expandable Strings

    When you use double-quoted strings, you can expand variables inside of them like this:

     
    PS C:\> "Windir: $env:windir"
    Windir: C:\Windows 
     

    However, there is no obvious way to mark the beginning and end of variables, so this will fail:

     
    PS C:\> "$env:windir: this is my Windows folder"
     this is my Windows folder 

    The solution is to use braces to identify the start end end of variables inside…

    • 9 Aug 2018
  • Power Tips: Finding Windows Build Numbers

    When you run winver.exe, you can easily retrieve the full Windows build number. Reading the build number from PowerShell is not as obvious. There is no a built-in cmdlet.

    However, it’s easy to create a simple function that does it for you:

    function Get-OSInfo
    {
      $path = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
      Get-ItemProperty -Path $path -Name CurrentBuild, UBR, Re…
    • 8 Aug 2018
  • Power Tips: Checking for USB Devices

    If you’d like to know whether a specific device is attached to your computer, you can use WMI to dump the names of all plug&play devices:

    Get-WmiObject -Class Win32_PnpEntity | 
      Select-Object -ExpandProperty Caption
    

    Twitter This Tip! ReTweet this Tip!

    • 7 Aug 2018
  • Power Tips: Using PSGraph

    PSGraph is an awesome free PowerShell library that you can use to visualize relationships. Before you can use PSGraph, you need to install its prerequisites (the graphviz engine). Both can be done if you have Administrator privileges:

    #requires -RunAsAdministrator
    
    # install prerequisite (graphviz)
    Register-PackageSource -Name Chocolatey -ProviderName Chocolatey -Location http://chocolatey.org/api/v2/
    Find-Package gr…
    • 6 Aug 2018
  • Power Tips: Using AD Filters with Cmdlets (Part 4)

    In the previous tip we started to look at how cmdlets from the ActiveDirectory module (part of the free RSAT tools) can filter results, and looked at combining filter expressions. Today let’s look at how to deal with date and time

    Some AD attributes contain date and time information, such as the date of last login. This type of information is represented as a very long 64-bit integer. You can use date and time in…

    • 3 Aug 2018
  • Power Tips: Using AD Filters with Cmdlets (Part 3)

    In the previous tip we started to look at how cmdlets from the ActiveDirectory module (part of the free RSAT tools) can filter results, and started to work our way into the fast and robust LDAP filters.

    LDAP filter has one strong requirement. You must use the original ActiveDirectory attribute names, and not the friendly names found in many PowerShell cmdlets. So „country“ would need to be the AD attribute name „co“.…

    • 2 Aug 2018
  • Power Tips: Using AD Filters with Cmdlets (Part 2)

    In the previous tip we started to look at how cmdlets from the ActiveDirectory module (part of the free RSAT tools) can filter results. You learned that the filters look like PowerShell code but in reality, they are not.

    For simple queries, the filters work well. However, once you use PowerShell language features other than operators, you will soon discover that the filter in reality is not using PowerShell code.

    If you…

    • 1 Aug 2018
  • Power Tips: Using AD Filters with Cmdlets (Part 1)

    The free RSAT tools come with the ActiveDirectory PowerShell module. You can use the cmdlets from this module to retrieve AD information such as user or group names. Cmdlets like Get-ADUser and Get-ADComputer support server-side filters. They work a bit different than you might think, though.

    For simple queries, these filters are easy to use. For example, this line gets you the first 5 users with names that start with…

    • 31 Jul 2018
  • Power Tips: Creating Temp File Names

    Whenever you write information to disk, it makes sense to use unique temporary file names. If you use static file names and run your code more than once, the same file would be overwritten time after time. If someone opened the file and locked it, this could cause your script to fail.

    Here are some easy approaches to generate temporary file names that are unique:

    # use a random number (slight chance of duplicates)
    $p…
    • 30 Jul 2018
  • Power Tips: File System Stress Test

    If you’d like to generate super large files for stress test purposes, you don’t have to waste time pumping data into a file to make it grow. Instead, simply set the desired file size to reserve the space on disk.

    This creates a 1GB test file:

     # create a test file
     $path = "$env:temp\dummyFile.txt"
     $file = [System.IO.File]::Create($path)
    
     # set the file size (file uses random content)
     $file.S…
    • 27 Jul 2018
  • Power Tips: Passing Commands via Parameter

    Here is a rather unusual use case for function parameters: a user can pass an output command:

    function Get-ProcessList
    {
      param
      (
        [string]
        [ValidateSet('GridView','String')]
        $OutputMode = 'String'
      )
      
      Get-Process | & "Out-$OutputMode"
      
    }
    
    # output as a string
    Get-ProcessList -OutputMode String
    # output in a grid view window
    Get-ProcessList -OutputMode GridView
    

    Twitter This Tip! ReTweet this…

    • 26 Jul 2018
  • Power Tips: Dealing with File Encoding and BOM

    When you write text content to a file, PowerShell cmdlets let you specify the encoding. Encoding determines how characters are stored, and when special characters appear garbled, this typically indicates that there is an encoding mismatch.

    However, there are some encoding settings that you cannot control via cmdlet parameters. Here is an example. Save a process list to CSV file:

    $Path = "$env:temp\export.csv"…
    • 25 Jul 2018
  • Power Tips: Finding Nested Active Directory Memberships (Part 3)

    In the previous tip we illustrated how you can find out the direct and indirect group memberships for a user. If you’d like to know the memberships for the current user, there is a much easier (and faster) approach: use the access token for the current user to retrieve the current effective group memberships:

    $groups = [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups.Translate([System.Security.Principal…
    • 24 Jul 2018
  • Power Tips: Finding Nested Active Directory Memberships (Part 2)

    In the previous tip we illustrated how you can use the cmdlets in the ActiveDirectory module to find all direct and indirect memberships for an Active Directory user.

    If you have no access to the ActiveDirectory module, PowerShell can also use pure .NET methods to get the memberships:

    function Get-NestedGroupMember
    {
      param
      (
        [Parameter(Mandatory,ValueFromPipeline)]
        [string]
        $distinguishedName
      )
    
      p…
    • 23 Jul 2018
  • Power Tips: Finding Nested Active Directory Memberships (Part 1)

    The ActiveDirectory module (part of the free RSAT tools) provides a number of AD cmdlets. One of these can dump all direct group memberships, for example:

     
    PS> Get-ADPrincipalGroupMembership  -Identity $env:username
     

    However, the cmdlet cannot list indirect group memberships, and it also has a bug: in some scenarios, it simply reports an „Unknown Error“.

    Here is a simple alternative dumping all group…

    • 20 Jul 2018
  • Power Tips: Progress Bar Timer

    Here is a simple example using the PowerShell progress bar. The code displays a progress bar counting down a break. Simply adjust the number of seconds you’d like to pause. You could use this example for displaying breaks in classes or conferences:

    $seconds = 60
    1..$seconds |
    ForEach-Object { $percent = $_ * 100 / $seconds; 
    
    Write-Progress -Activity Break -Status "$($seconds - $_) seconds remaining..."…
    • 19 Jul 2018
  • Power Tips: Automatic Document & Report Generation (Part 5)

    Iain Brighton has created a free PowerShell module called „PScribo“ that can be used to easily create documents and reports in text, html, or Word format.

    To use this module, simply run this command:

    # https://github.com/iainbrighton/PScribo 
    # help about_document 
    
    # create a folder to store generated documents 
    $OutPath = "c:\temp\out"
    $exists = Test-Path -Path $OutPath
    if (!$exists) { $null =
    • 18 Jul 2018
  • Power Tips: Automatic Document & Report Generation (Part 4)

    Iain Brighton has created a free PowerShell module called „PScribo“ that can be used to easily create documents and reports in text, html, or Word format.

    To use this module, simply run this command:

    Install-Module -Name PScribo -Scope CurrentUser -Force
    

    In the previous tips, we explained how you can generate dynamic tables. Today, find out how you can highlight individual table cells to indicate conditions…

    • 17 Jul 2018
  • Power Tips: Automatic Document & Report Generation (Part 3)

    Iain Brighton has created a free PowerShell module called „PScribo“ that can be used to easily create documents and reports in text, html, or Word format.

    To use this module, simply run this command:

    Install-Module -Name PScribo -Scope CurrentUser -Force
    

    In the previous tips, we explained how you can generate dynamic tables. Today, we’d like to show how easy it is to adjust tables, and display arbitrary data…

    • 16 Jul 2018