• 20 Oct 2017

    Creating Leading Zeros

    Did you ever need to convert numbers into strings with leading zeros, for example to compose server names? Simply use PowerShell’s “-f” operator: $id = 12 ' server{0:d4} ' -f $id Here is the output: server0012 The –f operator expects a text template on its left side, and value(s) on its right side. Inside the text template, use {x} as placeholder(s) for your values on the right side. Placeholders start...
    • 19 Oct 2017

    Demystifying Error Handling

    Any error in PowerShell code surfaces as an error record object. Check out the function below which extracts all relevant error information from such error record: function Get-ErrorInfo { param ( [ Parameter ( ValueFrompipeline )] [ Management.Automation.ErrorRecord ] $errorRecord ) process { $info = [ PSCustomObject ] @ { Exception = $errorRecord . Exception . Message Reason = $errorRecord . CategoryInfo...
    • 18 Oct 2017

    Determine Boot Time and Uptime Remotely

    Get-CimInstance is a useful cmdlet to retrieve WMI information because it uses standard .NET DateTime objects rather than the awkward WMI datetime format. However, Get-CimInstance uses WinRM for remote access whereas the older Get-WmiObject used DCOM for remote access. Very old systems may not yet be configured to use WinRM remoting, and may still require DCOM. Here is sample code that illustrates how you can use Get...
    • 17 Oct 2017

    Determine Boot Time and Uptime

    WMI can tell you when a system was booted, and this information can be re-calculated to find out the uptime: $bootTime = Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -ExpandProperty LastBootupTime $upTime = New-TimeSpan -Start $bootTime $min = [ int ] $upTime . TotalMinutes "Your system is up for $min minutes now." Note that Get-CimInstance uses WinRM remoting by default when you use...
    • 16 Oct 2017

    Pipe Information to Excel

    Here is a small yet very useful function that receives data from other cmdlets and sends them to Excel: function Out-Excel { param ( $path = " $env:temp\report$(Get-Date -Format yyyyMMddHHmmss).csv " ) $Input | Export-Csv $path -NoTypeInformation -UseCulture -Encoding UTF8 Invoke-Item $path } Simply pipe anything you want to Out-Excel. For example: PS C:\> Get-Process | Out-Excel ReTweet this...
    • 13 Oct 2017

    Evaluating Event Log Information

    Get-EventLog provides access to the content written to the classic Windows event logs. The most valuable information can be found in a secret property called ReplacementStrings. Here is an approach to make this information visible so you can examine it and build reports. In the example, the event ID 44 written by the Windows Update Client is retrieved, and the code outputs the replacement strings. They tell you exactly...
    • 12 Oct 2017

    Converting Weird Data Formats

    Sometimes, you stumble across weird data formats, i.e. in log files, that won’t autoconvert to DateTime objects. Here is a quick approach for parsing such date and time information: $weirdDate = ' 03 12 --- 1988 ' [ DateTime ] :: ParseExact ( $weirdDate , ' MM dd --- yyyy ' , $null ) As you can see, ParseExact() does the job for you and wants you to specify the custom date and time format, using the standard...
    • 11 Oct 2017

    Finding All Domain Controllers (no module required)

    In the previous tip we explained how you can use the ActiveDirectory module and its cmdlets to find all domain controllers in your organization, or perform any other LDAP query. Here is the same approach with pure .NET methods. It runs without the need for any additional PowerShell module and does not require the RSAT tools to be installed. It does require your computer to be member of an Active Directory. $ldapFilter...
    • 10 Oct 2017

    Find All Domain Controllers

    If you have installed the free Microsoft RSAT tools, you have access to the ActiveDirectory module. Here is a simple approach to find all domain controllers in your organization: #requires -Module ActiveDirectory $filter = ' (&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192)) ' Get-ADComputer -LDAPFilter $filter Basically, you can run any LDAP filter query. Simply choose the appropriate...
    • 9 Oct 2017

    Free Ebooks from Microsoft

    Microsoft is giving away unlimited numbers of free ebooks on many different topics. Ebooks can be downloaded using a PowerShell script. Here are the details: https://blogs.msdn.microsoft.com/mssmallbiz/2017/07/11/largest-free-microsoft-ebook-giveaway-im-giving-away-millions-of-free-microsoft-ebooks-again-including-windows-10-office-365-office-2016-power-bi-azure-windows-8-1-office-2013-sharepo/ And here is the link...
    • 6 Oct 2017

    Changing Network Connection Mode from Private to Public (and vice versa)

    Starting with Windows Server 2012 R2 and Windows 8.1, PowerShell ships with many useful cmdlets for client and server configuration. This comes handy as some settings can no longer be controlled via UI. For example, to change the network type of your network, simply run this code with Administrator privileges: PS> Get-NetConnectionProfile Name : internet-cafe InterfaceAlias : WiFi InterfaceIndex : 13 NetworkCategory...
    • 5 Oct 2017

    Removing Windows 10 Apps

    PowerShell is probably the easiest way to get rid of preinstalled Windows 10 apps. If you know the name of a particular app that you want to remove, launch PowerShell with Administrator privileges, and remove the app like this: PS> Get-AppxPackage *bingweather* | Remove-AppxPackage -WhatIf What if: Performing the operation "Remove package" on target "Microsoft.BingWeather_4.20.1102.0_x64__8wekyb3d8bbwe". PS> ...
    • 4 Oct 2017

    Launching Daily Tools via Alias

    You probably know the shortcut names that PowerShell predefines: Aliases like “dir” and “ls” help you save typing in everyday life. There are many good reasons to expand the list of aliases and include tools you use daily. For example, instead of clicking your way to the SnippingTool screenshot tool, why not add an alias: PS> Set-Alias -Name snip -Value snippingtool.exe PS> snip Next time you need to copy part...
    • 3 Oct 2017

    PowerShell 2 Now Considered Deprecated

    Microsoft just announced that PowerShell 2 will soon be labeled “deprecated”. It will still be available for some time, but this is a gentle hint that you should move away from it, and focus on PowerShell 5. PowerShell 2 is the default PowerShell available on Windows 7. Yet even on modern operating systems, PowerShell 2 may still be around. Let’s check how much your system is still impacted by PowerShell 2. The line...
    • 2 Oct 2017

    Repairing Disk Drives

    In the old days, disk repair was performed by chkdsk.exe. This still works. In Windows Server 2012 R2 and Windows 8.1, a new cmdlet called Repair-Volume was added. Like chkdsk.exe, it needs full Administrator privileges. You can use it to scan drives for errors: PS> Repair-Volume -Scan -DriveLetter c NoErrorsFound PS> You can also use the cmdlet to fix errors: -OfflineScanAndFix: Takes the volume offline...
    • 29 Sep 2017

    Finding Your Windows Product Key

    Knowing your Windows product key can be essential when you later need to restore your computer from a backup. Here is a simple one-liner to provide you with your product key information: ( Get-WmiObject -Class SoftwareLicensingService ) . OA3xOriginalProductKey ReTweet this Tip!
    • 28 Sep 2017

    Getting Cached Credentials

    In the previous tip we talked about a public module called PSCredentialManager that helps you manage cached credentials. Sometime, less is more, so when you look at the code you’ll soon discover that it is a console command called cmdkey.exe that actually interacts with Windows. To get a list of cached credentials on your local machine, all you really need is this: PS> cmdkey /list Currently stored credentials...
    • 27 Sep 2017

    Playing with PowerShell Gallery Content

    The public PowerShell Gallery ( www.powershellgallery.com ) is a place where PowerShell scripters can freely exchange scripts and modules. All you need is PowerShell 5 with PowerShellGet which provides you with the cmdlets required to interact with the Gallery. Of course, you are responsible for checking code and making sure it runs flawlessly and does not contain security issues. One of the available modules is...
    • 26 Sep 2017

    Calculating Folder File Size

    Measure-Object can also sum up property values. This is how you determine folder size. The following code calculates the complete folder size for your user profile (which can take some time depending on the number of files found). It simply sums up the property “Length” for all files: $size = ( Get-ChildItem -Path $home -Force -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum ) . Sum ...
    • 25 Sep 2017

    Counting Files Efficiently (Part 2)

    In the previous tip we looked at how to efficiently count items like files in a folder. Here are some more examples. Counting the number of files in a given folder is trivial in PowerShell: $count = Get-ChildItem -Path " $home\Desktop " -Force | Measure-Object | Select-Object -ExpandProperty Count "Number of files: $Count" Simply adjust Get-ChildItem to find out even more. Add -Recurse, for example, to...
    • 22 Sep 2017

    Counting Files Efficiently (Part 1)

    A quick and dirty approach for counting files could be this: ( Get-ChildItem -Path c:\windows).Count However, it would produce some memory load because all files would have to be accumulated in memory before Count property would retrieve the number of objects. When you search recursively, this can add up. A much less resource intensive approach uses Measure-Object like this: ( Get-ChildItem -Path c:\windows...
    • 21 Sep 2017

    Uncovering TinyUrls’ True Origin

    URL shortening is great for Twitter messages but hides the origin. Would you really trust http://bit.ly/e0Mw9w? Here is a simple approach that lets you uncover where a tiny URL really points to: $shortUrl = "http://bit.ly/e0Mw9w" $longURL = Invoke-WebRequest -Uri "http://untiny.me/api/1.0/extract?url=$shortUrl&format=text" -UseBasicParsing | Select-Object -ExpandProperty Content "'$shortUrl' -> '$longUrl...
    • 20 Sep 2017

    Creating Colorful Weather Report

    In the previous tip we explained how you can retrieve weather forecast data using Invoke-WebRequest. This was pure black-and-white text. To get a colorful report, on Windows 10 you can take advantage of control sequences supported by powershell.exe. Simply run the code below inside a PowerShell console: $City = ' Hannover ' ( Invoke-WebRequest "http://wttr.in/$City" -UserAgent curl ) . content -split "`n" By...
    • 19 Sep 2017

    Get Weather Forecast

    Invoke-WebRequest can easily retrieve web page content for you. If you run it without the –UseBasicParsing parameter, the HTML is even parsed by the Internet Explorer DOM. This way, PowerShell requires just a couple lines of code to retrieve the current weather forecast for almost any city in the world: $City = ' New York ' $weather = Invoke-WebRequest -Uri "http://wttr.in/$City" $text = $weather . ParsedHtml ...
    • 18 Sep 2017

    Avoid Read-Host

    Do you use Read-Host to receive user input? If you do, rethink. Read-Host always prompts a user, and there is no way to automate scripts that use Read-Host: $City = Read-Host -Prompt ' Enter City ' A much better easy way would look like this: param ( [ Parameter ( Mandatory )] $City ) This creates a mandatory parameter. If the user does not supply it, a prompt is created, very similar to Read-Host. Yet...