Blog - Post List
    • 13 Jul 2017

    Power Tips: Clearing All User Variables

    In the previous tip we illustrated how you can identify built-in PowerShell variables with an approach like this: $ps = [ PowerShell ] :: Create () $null = $ps . AddScript ( ' $null=$host;Get-Variable ' ) $ps . Invoke () $ps . Runspace . Close () $ps . Dispose () Now let’s do the opposite, and create a function that dumps only your own variables: function Get-UserVariable ( $Name = ' * '...
    • 12 Jul 2017

    Power Tips: Finding PowerShell Default Variables (Part 3)

    In the previous tip we illustrated how you can identify built-in PowerShell variables with an approach like this: $ps = [ PowerShell ] :: Create () $null = $ps . AddScript ( ' $null=$host;Get-Variable ' ) $ps . Invoke () $ps . Runspace . Close () $ps . Dispose () Apparently, this code still misses some variables that aren’t created by the PowerShell core engine, but instead are added later by...
    • 11 Jul 2017

    Power Tips: Finding PowerShell Default Variables (Part 2)

    In the previous tip we explained how you can use a separate new and fresh PowerShell to retrieve all default variables. When you examine these variables closely, you will discover that still some PowerShell variables are missing. Here is a slightly modified version called Get-BuiltInPSVariable that includes all reserved PowerShell variables: function Get - BuiltInPSVariable ( $Name = ' * ' ) { # create a...
    • 10 Jul 2017

    Power Tips: Finding PowerShell Default Variables (Part 1)

    Sometimes it would be useful to identify the automatic PowerShell variables managed by PowerShell so you could differentiate between built-in variables and your own. Get-Variable always dumps all variables. Here is a simple trick that uses a separate new and fresh PowerShell runspace to determine the built-in PowerShell variables: # create a new PowerShell $ps = [ PowerShell ] :: Create () # get all variables inside...
    • 7 Jul 2017

    Power Tips: Finding PowerShell Classes

    Starting in PowerShell 5, you can define PowerShell classes. They are defined dynamically and live in memory. So how would you know the names of classes that have been defined? Let’s first define a really simple class that does not do anything: class TestClass { } How would you be able to check whether a class named “TestClass” exists in memory? Here is a helper function called Get-PSClass...
    • 6 Jul 2017

    Power Tips: Using PowerShell Classes 2

    Starting in PowerShell 5, you can define PowerShell classes. You can use classes to create new objects, and by defining one or more “constructors”, you can easily initialize the newly created objects as well. Let’s have a look: class Employee { [ int ] $Id [ string ] $Name Employee ([ int ] $Id , [ string ] $Name ) { $this . Id = $Id $this . Name = $Name } Employee ([ string ] $Name...
    • 5 Jul 2017

    Power Tips: Using PowerShell Classes

    Starting with PowerShell 5, you can define classes. They have many use cases. One would be to create libraries of useful helper functions to better organize them. For this, a class would define “static” methods. Here is a simple example: class HelperStuff { # get first character of string and throw exception # when string is empty or multi-line static [ char ] GetFirstCharacter ([ string ] $Text ) ...
    • 4 Jul 2017

    Power Tips: Reading Registry Values (Workaround)

    In the previous tip we illustrated that Get-ItemProperty cannot read registry key values when there is a value present with corrupted content: PS> $key = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\History\{35378EAC-683F-11D2-A89A-00C04FBBCFA2}\0" PS> Get-ItemProperty -Path $key Get-ItemProperty : Specified cast is not valid. At line:1 char:1 ...
    • 3 Jul 2017

    Power Tips: Reading Registry Values Fails

    Occasionally, reading values of a registry key may fail with a strange error message: PS> $key = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\History\{35378EAC-683F-11D2-A89A-00C04FBBCFA2}\0" PS> Get-ItemProperty -Path $key Get-ItemProperty : Specified cast is not valid. At line:1 char:1 + Get-ItemProperty -Path $key + ~~~~~~~~~~~~~~~~~~~~~~~~~...
    • 30 Jun 2017

    Power Tips: Greetings of the Day (with Voice)

    In the previous tip we explained how you can add a personal greeting to your PowerShell profile. This greeting can also be spoken out, provided your volume is turned up. This works for all Powershell hosts including VSCode. This will add the code to your profile script: # create profile if it does not yet exist $exists = Test-Path -Path $Profile . CurrentUserAllHosts if ( ! $exists ) { $null = New-Item -Path...
    • 29 Jun 2017

    Power Tips: Greetings of the Day

    Here is a simple approach that takes an array of strings and returns a random string that you could use for custom greetings in PowerShell: $greetings = ' Hello there! ' , ' Glad to see you! ' , ' Happy coding! ' , ' Have a great day! ' , ' May the PowerShell be with you! ' $greetings | Get-Random All you need to do is add the code to your profile script, for...
    • 28 Jun 2017

    Power Tips: Truth about LINQ in PowerShell

    Lately there have been reports about using Linq, a .NET query language, with PowerShell in an effort to speed up code. Until there is true Linq support in PowerShell, using Linq is very cumbersome and requires strict typing and access to undocumented methods. What’s more, the same can be achieved with pure PowerShell approaches, and the speed increase often is just marginal – at least not very relevant to...
    • 27 Jun 2017

    Power Tips: Secret Windows 10 Transparency Mode

    When you open a native PowerShell console in Windows 10, you can hold down CTRL+SHIFT, then move your mouse wheel, to adjust console background color transparency, and let other windows shine through. The same works for cmd.exe as well, of course. ReTweet this Tip!
    • 26 Jun 2017

    Power Tips: Flush DNS Cache

    Windows is using a DNS cache, so when you change DNS servers, you need to flush the cache before the new settings take effect. PowerShell is a friend with old console commands, so you can simply run this line in PowerShell: PS> ipconfig /flushdns ReTweet this Tip!
    • 23 Jun 2017

    Power Tips: Displaying Folder Tree

    PowerShell is a friend with old console commands, so the easiest way of displaying the tree structure of a folder is the old “tree” command. It works best in a native PowerShell console because editors often use a different character set. Try this: PS> Tree $home Just make sure you are running this command in a native PowerShell console or VSCode. You can then pipe the result to clip.exe and paste...
    • 22 Jun 2017

    Power Tips: Using Cached Port File

    In the previous tip we explained how you can download port assignments via PowerShell from IANA. This process requires Internet access and can take a while. So here is code that looks for a cached CSV file. If it is present, port data is loaded from file offline, else the data is retrieved online, and a cache file is written. Note especially how Tee-Object is used to create the cache file: $url = ' https://www.iana...
    • 21 Jun 2017

    Power Tips: Get List of Port Assignments

    The IANA (Internet Assigned Numbers Authority) maintains a CSV file with all known port assignments. PowerShell can download this list for you: $out = " $env:temp\portlist.csv " $url = ' https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv ' $web = Invoke-WebRequest -Uri $url -UseBasicParsing -OutFile $out Import-Csv -Path $out -Encoding UTF8 The result...
    • 20 Jun 2017

    Power Tips: World Time Clock

    PowerShell 5 comes with Get-TimeZone which returns all defined time zones and their time offset. This is all you need for a one-liner world clock: $isSummer = ( Get-Date ) . IsDaylightSavingTime () Get-TimeZone -ListAvailable | ForEach-Object { $dateTime = [ DateTime ] :: UtcNow + $_ . BaseUtcOffset $cities = $_ . DisplayName . Split ( ' ) ' )[ - 1 ] . Trim () if ( $isSummer -and $_ . SupportsDaylightSavingTime...
    • 19 Jun 2017

    Power Tips: Check for Daylight Savings Time

    Here is how PowerShell can find out whether Daylight Savings Time is currently effective – a potentially needed detail when doing GMT calculations: ( Get-Date ) . IsDaylightSavingTime () ReTweet this Tip!
    • 16 Jun 2017

    Power Tips: Setting Time Zone

    While you need administrative privileges to adjust time and date on your computer, each user can change the time zone, i.e. when you travel. PowerShell 5 comes with a very simple family of cmdlets to manage time zones. First, check out your current setting: PS> Get-TimeZone Id : W. Europe Standard Time DisplayName : (UTC+01:00) Amsterdam, Berlin, Bern, Rom, Stockholm, Wien StandardName : Mitteleuropäische...
    • 15 Jun 2017

    Power Tips: Finding All Variables in a Script

    In the previous tip we illustrated how you can analyze the content of a script block and search for variables or commands. The same is possible for text-based scripts. The script below will analyze itself and dump variables and commands: $filepath = $PSCommandPath $tokens = $errors = $null $ast = [ System.Management.Automation.Language.Parser ] :: ParseFile ( $filepath , [ ref ] $tokens , [ ref ] $errors ) #...
    • 14 Jun 2017

    Power Tips: Finding All Variables in a Script Block

    To analyze the content of a script block, you can easily examine the AST, and, for example, create a list of all variables in the code: $code = { $a = "Test" $b = 12 Get-Service Get-Process $berta = 100 } $code . Ast . FindAll ( { $true } , $true ) | Where-Object { $_ . GetType () . Name -eq ' VariableExpressionAst ' } | Select-Object -Property VariablePath -ExpandProperty Extent...
    • 13 Jun 2017

    Power Tips: Running PowerShell Script as a Scheduled Task

    If you need to run a PowerShell script in regular intervals, why not run it as a scheduled task? Here are some lines that help you create a new scheduled task to run a PowerShell script at 6AM: #requires -Modules ScheduledTasks #requires -Version 3.0 #requires -RunAsAdministrator $TaskName = ' RunPSScriptAt6 ' $User = "train\tweltner" $scriptPath = "\\Server01\Scripts\find-newaduser.ps1"...
    • 12 Jun 2017

    Power Tips: Spying on Function Source Code

    Here is a quick way how to find the source code of PowerShell functions: $ { function : Clear - Host } | clip This would copy the Clear-Host source code to the clipboard, and when you paste it, you’ll see how Clear-Host works: $RawUI = $Host . UI . RawUI $RawUI . CursorPosition = @ { X = 0 ;Y = 0 } $RawUI . SetBufferContents ( @ { Top = -1 ; Bottom = -1 ; Right = -1 ; Left = -1 } , @ { Character =...
    • 9 Jun 2017

    Power Tips: Modern Alternative to More

    In a PowerShell console, you can continue to pipe to more, just like in cmd.exe, to view results page by page. However, more does not support real-time pipelining, so all data needs to be collected first. This can take a long time and burn much memory: dir c:\windows -Recurse -ea 0 | more A better way is to use PowerShell’s own paging mechanism: dir c:\windows -Recurse -ea 0 | Out-Host -Paging Note that...