Blog - Post List
    • 19 May 2017

    Power Tips: Escape Wildcards

    When you use the –like operator, it supports three wildcards: “*” representing any number of any characters, “?” representing one character, and “[a-z]” for a list of characters. In addition, and this is not widely known, it supports the PowerShell escape character “`” that you can use to escape the wildcards. So when you check for “*” in a string, this...
    • 18 May 2017

    Power Tips: Validating Integer Variables

    You can easily assign the [Int] type to a variable to make sure it can contain only digits. But did you know that you can also apply a regex validator (at least starting in PowerShell 4)? This way, you can define that a variable should be integer but can only have numbers between 2 and 6 digits, or any other pattern you require: PS> [ValidatePattern('^\d{2,6}$')][int]$id = 666 PS> $id = 10000 ...
    • 17 May 2017

    Power Tips: Creating Random MAC Addresses

    If you just need a bunch of randomly generated MAC addresses, and you don’t care much about whether these addresses are actually valid, then here is a one liner: PS> (0..5 | ForEach-Object { '{0:x}{1:x}' -f (Get-Random -Minimum 0 -Maximum 15),(Get-Random -Minimum 0 -Maximum 15)}) -join ':' a5:66:07:6d:d9:18 PS> (0..5 | ForEach-Object { '{0:x}{1:x}' -f (Get-Random -Minimum 0 -Maximum...
    • 16 May 2017

    Power Tips: Bitwise Shift

    PowerShell contains some binary operators that are not so commonly used, for example bitwise shifting. The -shl operator shifts bits to the left: PS> 1 -shl 1 2 PS> 2 -shl 1 4 PS> 3 -shl 1 6 ReTweet this Tip!
    • 15 May 2017

    Power Tips: Converting Binary String to Integer

    Here is how you convert a binary text string into the corresponding integer value: $binary = "110110110" $int = [ Convert ] :: ToInt32 ( $binary , 2 ) $int Going the other way is even easier: PS> [Convert]::ToString(438,2) 110110110 ReTweet this Tip!
    • 12 May 2017

    Power Tips: Using Clipboard to Transfer Data and Results

    Finally in PowerShell 5, there is support for sending results to the clipboard, and receiving results from the clipboard: PS> Get-Command -Noun Clipboard CommandType Name Version Source ----------- ---- ------- ------ Cmdlet Get-Clipboard Microsoft.PowerShell.Management Cmdlet Set-Clipboard Microsoft.PowerShell.Management For example, you can open Excel with some sheets of data, copy a column...
    • 11 May 2017

    Power Tips: Installing MSI on Remote System

    Here is some code that may or may not work for you. It requires that you have Admin access to a remote system. $ComputerName = ' NameOfMachineToInstall ' $TargetPathMSI = ' \\softwareserver\product\package.msi ' $class = [ wmiclass ] "\\$ComputerName\ROOT\cimv2:Win32_Product" $class . Install ( $TargetPathMSI ) If permissions and network connectivity allow for it, this code installs...
    • 10 May 2017

    Power Tips: How .Replace() and -replace differ

    There are two ways of replacing text in a string: the Replace() method, and the –replace operator. They work fundamentally different. Replace() is case-sensitive and replaces text with new text: PS> 'Hello World.'.Replace('o', '0') Hell0 W0rld PS> 'Hello World.'.Replace('ell','oo') Hooo World The -replace operator is by default case-insensitive (use...
    • 9 May 2017

    Power Tips: HTML Encoding Advanced

    The static .NET method HtmlEncode does a good job encoding the usual character codes but fails with many special characters. To encode all characters correctly, here is a function called ConvertTo-EncodedHtml: function ConvertTo - EncodedHTML ( $HtmlText ) { $chars = [ Web.HttpUtility ] :: HtmlEncode ( $HtmlText ) . ToCharArray () $txt = New-Object System.Text.StringBuilder $null = . { foreach ( $c in $chars...
    • 8 May 2017

    Power Tips: HTML Encoding

    There is a static .NET method that you can use to HTML-encode text, for example if you want the text to display correctly in HTML output: PS> [System.Web.HttpUtility]::HtmlEncode('Österreich heißt so.') Österreich heißt so. ReTweet this Tip!
    • 5 May 2017

    Power Tips: Bulk Printing Word Documents

    This line finds all Word documents in your profile: Get-ChildItem -Path $home -Filter * . doc * -Recurse If you’d like, you can easily print them all. Here is how: Get-ChildItem -Path $home -Filter * . doc * -Recurse | ForEach-Object { Start-Process -FilePath $_ . FullName -Verb Print -Wait } The most important part of this is the –Wait parameter: if you omit it, PowerShell would try and print...
    • 5 May 2017

    Power Tips: Downloading Videos From German Media Databases

    In Germany, there are publicly available media databases with most of the TV content broadcasted by public stations. It just takes very little PowerShell code to extract the JSON data, display the TV shows in a list, and let you select some for download. Note however that the JSON file with the download URLs is quite large, so it may take a moment for the video list to appear. #requires -Version 3.0 # here is the...
    • 3 May 2017

    Power Tips: Translating Error Records

    Whenever PowerShell records an error, it wraps it in an Error Record object. Here is a function that takes such an error record and extracts the useful information: #requires -Version 3.0 function Get-ErrorDetail { param ( [ Parameter ( Mandatory , ValueFromPipeline )] $e ) process { if ( $e -is [ Management.Automation.ErrorRecord ]) { [ PSCustomObject ] @ { Reason = $e . CategoryInfo . Reason Exception...
    • 2 May 2017

    Power Tips: Enable AD Users with Out-GridView

    Sometimes it requires just a couple of lines of code in PowerShell to produce highly useful helpdesk tools. Here is one that displays all currently disabled AD users. You can select one (or many by holding CTRL), and once you click OK, these users will be enabled: #requires -Version 3.0 -Modules ActiveDirectory Search-ADAccount -AccountDisabled | Out-GridView -Title ' Who should be enabled? ' -OutputMode...
    • 1 May 2017

    Power Tips: Turning AD User into a Hash Table

    Sometimes it could be useful to load all attributes from a given AD user into a hash table. This way, you could edit them, and then use Set-ADUser with its -Add or -Replace parameters to apply them to another user account. Here is how you read in all AD User attributes into a hash table: #requires -Version 3.0 -Modules ActiveDirectory $blacklist = ' SID ' , ' LastLogonDate ' , ' SAMAccountName...
    • 28 Apr 2017

    Power Tips: Cloning Folder Structures (with NTFS Permissions) – Part 2

    In the previous tip we illustrated how Get-FolderStructureWithPermission can document and create a list of all nested folders in a structure, along with their respective NTFS security settings. The result could be saved in a variable, or serialized to disk using Export-Csv Today we show you the second part: once you have the information about a given folder structure, here is Set-FolderStructureWithPermission. It accepts...
    • 27 Apr 2017

    Power Tips: Cloning Folder Structures (with NTFS Permissions) – Part 1

    Sometimes you need to re-create a nested folder structure, and may also want to clone the NTFS permissions. Today we are tackling the first step: recording an existing folder structure along with NTFS permissions in SDDL form. This task is accomplished by Get-FolderStructureWithPermission. It accepts a path to an existing folder, then returns all of its child folders along with their NTFS permissions in SDDL form: ...
    • 26 Apr 2017

    Power Tips: Evaluating Exit Codes (aka Error Level – Part 3)

    In part 3 of our mini-series about running console applications in PowerShell, here is a goodie: how can you run a console application separately from PowerShell, and still get notified when it is done, and retrieve its exit code? Here is how: the code below runs ping.exe in a separate (hidden) window. PowerShell continues and is free to do whatever it wants. In the example, it outputs a number of “dot”...
    • 25 Apr 2017

    Power Tips: Evaluating Exit Codes (aka Error Level – Part 2)

    When you directly launch a console-based application, PowerShell returns its exit code (aka Error Level) in the automatic variable $LASTEXITCODE. However, how do you get the exit code for a console-based application that you launch via Start-Process? Here is how: $hostname = ' ' # run the console-based application synchronously in the PowerShell window, # and return the process object...
    • 24 Apr 2017

    Power Tips: Evaluating Exit Codes (aka Error Level – Part 1)

    When running a console-based application, it typically returns a numeric exit code. The meaning of this exit code is up to the console-based application, and you’d have to look it up there. PowerShell does hand you the exit code, though. It surfaces in $LASTEXITCODE. Here is an example using ping.exe to test for network response: $hostname = ' ' # run console-based executable...
    • 21 Apr 2017

    Power Tips: Ejecting CD Drive

    Here is a fun little function that uses WMI to eject your CD drive. It does so by first asking WMI for all CD drives. It then uses the explorer object model to navigate to the drive and call its context menu item “Eject”: function Eject-CD { $drives = Get-WmiObject Win32_Volume -Filter "DriveType=5" if ( $drives -eq $null ) { Write-Warning "Your computer has no CD drives to eject."...
    • 20 Apr 2017

    Power Tips: Identifying CSV Delimiter

    When importing a CSV file with Import-Csv, you need to specify a delimiter, and if you pick the wrong one, import obviously fails. You need to know the delimiter a CSV file is using. Here is a simple approach that tells you the delimiter for a given CSV file: function Get - CsvDelimiter ( $Path ) { # get the header line $headerLine = Get-Content $Path | Select-Object -First 1 # examine header line per character...
    • 19 Apr 2017

    Power Tips: Identifying Duplicate CSV Headers (Part 2)

    When a CSV file contains duplicate column headers, it cannot be imported. In the previous tip we illustrated how you can detect duplicate column headers in a CSV file. Now here is an approach that auto-corrects duplicate entries. First, you need a CSV file with duplicate column headers. On German systems, for example, you could create one like this: PS C:\> driverquery /V /FO CSV | Set-Content -Path $env:temp...
    • 18 Apr 2017

    Power Tips: Identifying Duplicate CSV Headers (Part 1)

    CSV files are just text files, so it is easy to strip the first line and examine its headers. If you don’t have a CSV file at hand, here is a simple line to create one to play with: PS C:\> Get-Process | Export-Csv -Path $env:temp\test.csv -NoTypeInformation -Encoding UTF8 -UseCulture PS C:\> Now you can analyze its headers. This simple approach tells you whether there are duplicate headers in a CSV...
    • 17 Apr 2017

    Power Tips: Serializing Date and Time in a Culture-Invariant Way

    When you save date and time to text, for example when exporting to CSV, or when creating text reports, DateTime objects are converted to the date and time format defined in your regional settings: PS> $date = Get-Date -Date '2017-02-03 19:22:11' PS> "$date" 02/03/2017 19:22:11 PS> $date.ToString() 03.02.2017 19:22:11 PS> Get-Date -Date $date -DisplayHint DateTime Freitag, 3. Februar...