Blog - Post List
    • 8 Dec 2016

    Power Tips: Most Popular Verbs

    Let’s explore which command verbs are most popular in your PowerShell: Get-Command -CommandType cmdlet , function | Group-Object -Property Verb | Sort-Object -Property Count -Descending Here is the result on our system: Count Name Group ----- ---- ----- 456 Get {Get-AppBackgroundTask, Get-AppvVirtualProcess... 210 Set {Set-AssignedAccess, Set-AutologgerConfig, Set... 120 Remove {Remove-AutologgerConfig...
    • 7 Dec 2016

    Power Tips: Safely Encrypting and Decrypting Text

    When you encrypt secret information, the challenge is to find a good secret. One particular safe secret would be your Windows identity, paired with your computer’s identity. This can be used to encrypt sensitive personal information on a particular computer. Here are two functions that illustrate how it’s done: function Decrypt-Text { param ( [ String ] [ Parameter ( Mandatory , ValueFromPipeline...
    • 6 Dec 2016

    Power Tips: Watch Out When Combining -Force and -WhatIf!

    The -WhatIf common parameter turns on simulation mode, so a cmdlet won’t change anything and instead report what it “would have” changed. This works perfectly well, unless a developer fails to implement -WhatIf correctly. This is rare, but there is a pattern: when you specify -Force and -WhatIf, the right thing would be to let -WhatIf win. Some developers are so focused on -Force that they let -Force...
    • 5 Dec 2016

    Power Tips: Creating File Shares

    In Server 2012 R2 and Windows 8.1, there are many useful new modules with cmdlets such as New-SmbShare which creates new file shares easily. If you don’t have these cmdlets, you can often use WMI instead. That requires more investigation and googling, but once you have a code template, it works well. To create new file shares as an Administrator, for example, try this: $share = [ wmiclass ] "Win32_Share"...
    • 2 Dec 2016

    Power Tips: Using Custom Scopes to Discard Any Output

    Yesterday we looked at custom scopes to automatically restore variables and clean up behind your code. Custom scopes can also be used to discard any output emitted by any part of code inside your scope. To do that, use this structure: $null = . { [code] }. Whatever you execute in the braces will run, and all variables and functions you might create will work outside of the scope, but there will not be any output. ...
    • 1 Dec 2016

    Power Tips: Using Custom Scopes

    When you change variables, you might need to clean up later and ensure that you reverted them back to some default value – unless you use custom scopes. Yesterday, we looked at how console application errors can be handled, and when you look at the code again, you see that a lot of effort was taken to restore the $ErrorActionPreference system variable: try { # set the preference to STOP $old = $ErrorActionPreference...
    • 30 Nov 2016

    Power Tips: Catching Errors from Native EXEs

    Ever wondered how you can catch errors emitted by native console EXEs? PowerShell’s error handlers can only deal with .NET code. Here is the framework to use when you’d like to catch console application errors: try { # set the preference to STOP $old = $ErrorActionPreference $ErrorActionPreference = ' Stop ' # RUN THE CONSOLE EXE THAT MIGHT EMIT AN ERROR, # and redirect the error channel...
    • 29 Nov 2016

    Power Tips: Advanced Error Handling: Rethrowing Exceptions

    When you handle errors, you may sometimes want to replace the original exception with your own. Here is a sample: function Do-Something { # function uses internal error handling try { Get-Process -Name NotThereOhWell -ErrorAction Stop } # catch this error type catch [ Microsoft.PowerShell.Commands.ProcessCommandException ] { $oldE = $_ . Exception # handle the error, OR SHOWN HERE: issue a new exception...
    • 28 Nov 2016

    Power Tips: Launching Applications as Someone Else

    Let’s assume you would like to open multiple PowerShell consoles running under different identities – or launch whatever application you require, just as someone else. To do that, you would have to log on as someone else, and obviously that’s a strain. So here is a way to save credentials to file in a safe way: the password is encrypted using your identity and your machine as a secret. You can get...
    • 25 Nov 2016

    Power Tips: Shed Light into the PowerShell Version Jungle

    Meanwhile, there are five major versions of PowerShell around. Toss in the new minor versions such as PowerShell 5.1 on Windows 10 and Server 2016. Spice this with beta versions and prerelease editions, and serve with PowerShell on Linux or Nano Server. Whew. It’s not easy to keep track, and understand which version you are using, where it came from, and what compatibility issues may exist. MVP colleague Jan Egil...
    • 24 Nov 2016

    Power Tips: Fixing PowerShell 5 Help Bug

    When you download PowerShell help via Update-Help, there was a bug in PowerShell 5 that might be fixed by now: text-based help files had the extension “.txt” rather than “.help.txt”, so PowerShell help would ignore them. Check for yourself – the command below should return tons of about topics: PS C:\> Get-Help about* Name Category Module Synopsis ---- -------- ------ -------- about_Aliases...
    • 23 Nov 2016

    Power Tips: Prohibiting Positional Parameters

    When you create PowerShell functions, parameters can be named or positional. Here is an example: If you’d like to detect illegal characters in file paths, here is a slight adaption: function Test-Command { param ( [ string ] $Name , [ int ] $Id ) "Name: $Name ID: $ID" } Test-Command -Name Weltner -Id 12 Test-Command Weltner 12 As you can easily spot, using positional parameters...
    • 22 Nov 2016

    Power Tips: Using Named Parameters in PowerShell Functions

    When you create a PowerShell function, all parameters are positional until you start adding the “Position” attribute. Once you start to do this, all parameters with no “Position” are suddenly named and must be specified. Have a look: Here is a classic function declaration, producing three positional parameters: function Test-Command { param ( [ string ] $Name , [ int ] $ID , [ string...
    • 21 Nov 2016

    Power Tips: Launching PowerShell Hidden

    Sometimes a PowerShell script should just produce something, for example a report, which then opens in Excel or notepad. You don’t want to necessarily show the PowerShell console window while PowerShell is active. There is no easy way to hide PowerShell’s console window because even the parameter -WindowStyle Hidden will first show the console and hide it only after it showed. One way is to use a Windows...
    • 18 Nov 2016

    Power Tips: Time Zone Management in PowerShell 5.1

    PowerShell 5.1 (available on Windows 10 and Server 2016) comes with some new cmdlets to manage computer time zones. Get-TimeZone returns the current settings, and Set-TimeZone would change it: PS C:\> Get-TimeZone Id : W. Europe Standard Time DisplayName : (UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna StandardName : W. Europe Standard Time DaylightName : W. Europe Daylight Time BaseUtcOffset ...
    • 17 Nov 2016

    Power Tips: Exploring Function Source Code

    The only fundamental difference between cmdlets and functions in PowerShell is the way how they are programmed: functions use plain PowerShell code, which is why it might be interesting to look at their source code, and learn new things. Here is a line that lists all PowerShell functions that are currently loaded from modules: Get-Module | ForEach-Object { Get-Command -Module $_ . Name -CommandType Function } ...
    • 16 Nov 2016

    Power Tips: Running 32-bit Code on the Same Machine

    If you need to run 32-bit PowerShell code from within a 64-bit script, and provided you are Administrator and use remoting, you can remote against your own system: $code = { [ IntPtr ] :: Size Get-Process } Invoke-Command -ScriptBlock $code -ConfigurationName microsoft.powershell32 -ComputerName $env:COMPUTERNAME This will run the script block contained in $code in a 32-bit environment. The pointer returns...
    • 15 Nov 2016

    Power Tips: Modern Replacement for systeminfo.exe

    For ages, systeminfo.exe returned all profiling information for a computer, and could made object-oriented in Powershell – somewhat: PS C:\> $info = systeminfo.exe /FO CSV | ConvertFrom-Csv PS C:\> $info.Domain WORKGROUP PS C:\> $info.'Logon Server' \\DESKTOP-7AAMJLF In PowerShell 5.1 (available on Windows 10 and Server 2016), there is finally a modern alternative: PS C:\> Get-ComputerInfo...
    • 14 Nov 2016

    Power Tips: Built-In Support for Local Accounts

    Beginning in PowerShell 5.1, there is finally built-in support for local user accounts. PowerShell 5.1 is currently available with Windows 10 and Windows Server 2016: PS C:\> Get-Command -Module *LocalAccounts | Select-Object -ExpandProperty Name Add-LocalGroupMember Disable-LocalUser Enable-LocalUser Get-LocalGroup Get-LocalGroupMember Get-LocalUser New-LocalGroup New-LocalUser Remove-LocalGroup Remove-LocalGroupMember...
    • 11 Nov 2016

    Power Tips: Careful with Add-Member!

    Frequently, Add-Member is used to create custom objects, for example like this: $o = New-Object -TypeName PSObject $o | Add-Member -MemberType NoteProperty -Name Notes -Value ' Something ' $o | Add-Member -MemberType NoteProperty -Name Date -Value ( Get-Date ) $o This works, and the result looks like this: PS C:\> $o Notes Date ----- ---- Something 10/28/2016 3:56:53 PM However, it is...
    • 10 Nov 2016

    Power Tips: How PSCustomObject Really Works

    In a previous tip we explained how PSCustomObject can create new objects really fast: $o = [ PSCustomObject ] @ { Date = Get-Date BIOS = Get-WmiObject -Class Win32_BIOS Computer = $env:COMPUTERNAME OS = [ Environment ] :: OSVersion Remark = ' Some remark ' } In reality, [PSCustomObject] is not a type, and you are not casting a hash table, either. What truly happens behind the scenes is the combination...
    • 9 Nov 2016

    Power Tips: Fast Approach to Creating New Objects

    To wrap up multiple pieces of information, you best store them in custom objects. The easiest and fastest way is to use the PSCustomObject: #requires -Version 3.0 $o = [ PSCustomObject ] @ { Date = Get-Date BIOS = Get-WmiObject -Class Win32_BIOS Computer = $env:COMPUTERNAME OS = [ Environment ] :: OSVersion Remark = ' Some remark ' } Inside the braces, you assign pieces of information (or command...
    • 8 Nov 2016

    Power Tips: Exploiting Your Command History

    PowerShell “records” all your interactive command input to its command history, and Get-History shows them. If you played around with PowerShell for a while and then decided that it wasn’t all that bad what you did, here is a script that copies all interactive commands from command history to your clipboard. You can then paste it into the PowerShell ISE, and make it a script: # define how old your...
    • 7 Nov 2016

    Power Tips: Getting Latest PowerShell Gallery Module Version

    On www.powershellgallery.com , Microsoft hosts a public script and module repository where you can exchange PowerShell code with others (see more on their site). To use the repository, you either need PowerShell 5 or install the PowerShellGet module manually (which is available for download on powershellgallery.com). You then have cmdlets like Find/Save/Install/Update/Remove-Script/Module. What’s missing is...
    • 4 Nov 2016

    Power Tips: Testing Files and Folders (separately)

    Test-Path is highly useful to test whether a file or folder exists, and it can be used with any of the PowerShell drives, so it can also test whether a variable, a function, or a certificate exists (for example). In recent PowerShell versions, Test-Path can now differentiate between containers (i.e. folders) and leafs (i.e. files), too: $path = ' c:\windows\explorer.exe ' # any item type Test-Path -Path...