Blog - Post List
    • 29 May 2017

    Power Tips: Validating Variables

    Variables and function parameters can be automatically validated through validation attributes. Here is a simple example making sure $test1 can only store values between 1 and 10: [ ValidateRange ( 1 , 10 )] $test1 = 10 Once you assign a value less than 1 or greater than 10 to it, PowerShell throws an exception. You just don’t have any control over the exception text. By using a script validator, you can...
    • 26 May 2017

    Power Tips: Cloning DHCP Server Settings

    Beginning with Windows Server 2012, you can easily export and re-import DHCP settings. Cloning or migrating DHCP servers is a snap. The example below exports the settings from \\ORIGDHCP and imports them into the local DHCP Server: Export-DHCPServer -File " $env:temp\dhcpsettings.xml " -Computername ORIGDHCP Import-DHCPServer -File " $env:temp\dhcpsettings.xml " ReTweet this Tip!
    • 25 May 2017

    Power Tips: Searching for ADUsers

    The free Microsoft RSAT tools come with the PowerShell “ActiveDirectory” module: plenty of cmdlets help you administer Active Directory users and computers. One cmdlet is especially useful. Rather than trying to find AD users with Get-ADUser and complex filters, use Search-ADAccount instead. It is specialized in finding users based on common scenarios. This line, for example, finds all user accounts that...
    • 24 May 2017

    Power Tips: Generating Random Passwords

    Here is a very simple way to create complex random passwords: Add-Type -AssemblyName System.Web $PasswordLength = 12 $SpecialCharCount = 3 [ System.Web.Security.Membership ] :: GeneratePassword ( $PasswordLength , $SpecialCharCount ) The API call lets you choose the length of the password, and the number of non-alphanumeric characters it contains. ReTweet this Tip!
    • 23 May 2017

    Power Tips: ToString() Masquerade

    In the previous tip we explained that ToString() is a fuzzy way of describing an object, and that the object author can decide what ToString() returns. This is especially true for your PowerShell code. Have a look how easily you can overwrite ToString() for any object: PS> $a = 1 PS> $a | Add-Member -MemberType ScriptMethod -Name toString -Value { 'go away' } -Force PS> $a go away PS> $a.GetType...
    • 22 May 2017

    Power Tips: Careful with ToString()

    Any .NET object has a method ToString() that returns a text representation. This is also what you get when you output an object in a string. However, the value returned by ToString() can vary, and you should never use it to make critical assumptions. Here is an example – these lines both produce a FileInfo object which represents the exact same file. Only the way how the object was created is different. All object...
    • 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...