• 18 Jan 2017

    Bulk Renaming Photos

    Here is a quick and fast way to bulk-rename files like photos, or other files. Have a look: #requires -Version 1.0 $Path = " $home\Pictures " $Filter = ' *.jpg ' Get-ChildItem -Path $Path -Filter $Filter | Rename-Item -NewName { $_ . name -replace ' DSC ' , ' TEST ' } Simply adjust the path and the filter to target the files. In the example, all *.jpg files in the pictures...
    • 17 Jan 2017

    Identifying Locked AD Accounts

    When searching for specific AD accounts, you may have used Get-ADUser in the past, and filtered results with a filter parameter. Such filters can grow quite complex, though. That’s why there is a shortcut for the most common AD searches. Simply use Search-ADAccount: #requires -Modules ActiveDirectory Search-ADAccount -AccountDisabled Search-ADAccount -AccountExpired Search-ADAccount -AccountInactive...
    • 16 Jan 2017

    Exploring Local Account Management Cmdlets

    PowerShell 5.1 (shipping with Windows 10 and Server 2016) can now natively manage local accounts. In the previous tip you learned how to use Get-LocalUser. To explore other cmdlets for local account management, here is how you identify the module that exposes Get-LocalUser, and then list other cmdlets provided by that module: #requires -Modules Microsoft.PowerShell.LocalAccounts # find module that defines this...
    • 13 Jan 2017

    Managing Local Users

    PowerShell 5.1 finally ships with cmdlets to manage local user accounts. To get a list of local user accounts, use Get-LocalUser and pipe the result to Select-Object to see all properties: PS C:\> Get-LocalUser | Select-Object -Property * AccountExpires : Description : Predefined Account to manage computer or domain Enabled : False FullName : PasswordChangeableDate : PasswordExpires : UserMayChangePassword...
    • 12 Jan 2017

    Getting AD User Attributes

    By default, Get-ADUser (provided by ActiveDirectory module which is part of the free Microsoft RSAT tools) retrieves only a few default properties. To get more information, use the –Properties parameter, and specify the properties you are after. To get a list of all AD users with their notes and description fields, try this: #requires -Modules ActiveDirectory Get-ADUser -Filter * -Properties Description ,...
    • 11 Jan 2017

    Careful with Get-Credential and SecureStrings

    Sometimes, scripts interactively ask for credentials, or passwords. Always be aware that the script author can get to the plain text of all entered information. Only enter sensitive information if you trust the script and author. Please note: this is not a PowerShell issue. It is a general issue with all software. Let’s see how a script could exploit an entered password. If a script asks for a complete credential...
    • 10 Jan 2017

    Managing Credentials (Part 5)

    When PowerShell auto-encrypts a secure string, it uses your identity as secret. Only you can decrypt the secure string. What if you want to encrypt a secret with a shared passphrase? Here is one classic approach, using a passphrase for encryption: # $secretKey MUST be of length 8 or 16 # anyone who knows the secret can decrypt the password $secretKey = ' mysecretmysecret ' $password = ' myPassword...
    • 9 Jan 2017

    Managing Credentials (Part 4)

    In the previous script we showed how you can save a credential object in encrypted form to disk. A similar approach just saves the secret password as encrypted text. This creates the encrypted password file: # read in the password, and save it encrypted $text = Read-Host -AsSecureString -Prompt ' Enter Password ' $text | Export-Clixml -Path " $home\desktop\mypassword.xml " It can only be read...
    • 6 Jan 2017

    Managing Credentials (Part 3)

    For unattended scripts, it is generally unsafe and not recommended to hard-code secret passwords into a script. As an alternative, you could ask for the password once, then create a credential object and use it wherever needed in your script. This part asks for a password, then constructs a credential object: $password = Read-Host -AsSecureString -Prompt ' Enter Password ' $username = ' myCompany\myUserName...
    • 5 Jan 2017

    Managing Credentials (Part 2)

    For scripts running unattended, you can create login credentials from code. This requires the secret password to be saved as clear text in a script (which obviously is unsafe unless you encrypt your script with the encrypting file system (EFS) or take other measures to protect the content): $password = ' topsecret! ' | ConvertTo-SecureString -AsPlainText -Force $username = ' myCompany\myUserName '...
    • 4 Jan 2017

    Managing Credentials (Part 1)

    Let’s assume you need to run a script every day that requires credentials. A safe way of storing credentials is to save them encrypted in a file. This code asks for credentials, then saves them in an XML file on your desktop: $credential = Get-Credential -UserName train\user02 -Message ' Please provide credentials ' $credential | Export-Clixml -Path " $home\desktop\myCredentials.xml " The...
    • 3 Jan 2017

    Parsing Raw Text (Part 3)

    In the previous tip we illustrated how you can use Select-String to find lines in raw text containing a specific word. It took some effort to extract the actual value(s) representing a given pattern: PS C:\> $data = ipconfig | select-string 'IPv4' PS C:\> [regex]::Matches($data,"\b(?:\d{1,3}\.){3}\d{1,3}\b") | Select-Object -ExpandProperty Value 192.168.2.112 This effort is not necessary...
    • 2 Jan 2017

    Parsing Raw Text (Part 2)

    In the previous tip we explained how you can use Select-String and a regular expression to extract valuable information from raw text results: PS C:\> $data = ipconfig | select-string 'IPv4' PS C:\> [regex]::Matches($data,"\b(?:\d{1,3}\.){3}\d{1,3}\b") | Select-Object -ExpandProperty Value 192.168.2.112 PowerShell supports the -match parameter which also matches regular expressions. It...
    • 30 Dec 2016

    Parsing Raw Text (Part 1)

    Sometimes, you may want to extract valuable information from pure text results. One easy way is the use of Select-String. This example extracts only the text lines containing “IPv4”: PS C:\> ipconfig | Select-String 'IPv4' IPv4 Address. . . . . . . . . . . : 192.168.2.112 If you are just interested in the actual IP address, you can refine the result and use a regular expression to extract...
    • 29 Dec 2016

    Adjusting Simple UIs

    In the previous tip you learned how you can use Show-Command to create simple UIs for text-based commands: #requires -Version 3.0 function Send-MailMessageUI { Show-Command -Name Send-MailMessage } Send-MailMessageUI If you’d like to adjust the number of parameters that show up in the UI, simply write your own functions. In the below example, Send-MailMessage is wrapped inside a custom function that...
    • 28 Dec 2016

    Creating Simple UIs

    Function and cmdlet parameters basically are the technique how PowerShell creates „user interfaces“. These text-based interfaces can easily be turned into graphical interfaces. If you’d like to send a mail message, you could use Send-MailMessage and provide the details via text-based parameters. Or, you could create a graphical interface and name it Send-MailMessageUI: #requires -Version 3.0 function...
    • 27 Dec 2016

    Extending Robocopy

    PowerShell can add value to existing commands such as robocopy. Take a look at the below function--it uses robocopy to copy files, and adds the ability to perform a „Flat Copy“ as well as the option to open the destination folder after the copy is done: #requires -Version 3.0 function Copy-FileWithRobocopy { param ( [ Parameter ( Mandatory )] [ string ] $Source , [ Parameter ( Mandatory )] ...
    • 26 Dec 2016

    Copy Color-Coded Code

    When you select code in the PowerShell ISE and copy it to the clipboard, it is copied in RTF format and preserves all color coding and font information. You can paste it in RTF-aware applications such as Word, and receive nicely formatted and color-coded PowerShell code. To adjust the font size, you cannot use the slider in the lower right-hand side of the PowerShell ISE. This slider just scales the font inside the...
    • 23 Dec 2016

    Creating WinForms GUIs in PowerShell

    While it is recommended to use the modern WPF technology to create PowerShell user interfaces, you might still want to occasionally use the older WinForms technique, especially if you need to target machines without .NET framework 3.51 or better. WinForms user interfaces require a lot of code, and it’s not particular intuitive. So here is a URL to a free graphical PowerShell online editor that creates the code...
    • 22 Dec 2016

    Using “Exit” to Communicate with Linux

    When a PowerShell script ends, you can run the command “Exit” and submit a numeric value. This has been good practice in the Windows world to set the “Error Level” that can be read by the caller (for example, a batch file or the scheduled task manager). exit 99 Now that PowerShell is available on Linux as well, it can also be used to report back a status number to the calling Linux process...
    • 21 Dec 2016

    Capturing Linux Output

    If you run PowerShell on Linux, you can combine Linux and PowerShell commands. To take the output of a Linux command and assign it to a PowerShell variable, do something like this: $content = ( ls ) Note that “ls” is an alias on Windows systems but refers to the original ls command on Linux systems. ReTweet this Tip!
    • 20 Dec 2016

    Test for File or Folder

    Test-Path can check whether a file or folder exists. If you add -PathType and specify Leaf (for files) or Container (for folders), the result can be even more specific: $path = ' c:\windows ' Test-Path -Path $path Test-Path -Path $path -PathType Leaf Test-Path -Path $path -PathType Container ReTweet this Tip!
    • 19 Dec 2016

    System Memory, Units, and Rounding

    Sometimes, you’d like to use different units of measurements. The total system memory is reported in bytes, for example. Here are some examples how you can turn bytes into GB and still make the result look nice: $memory = Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty TotalPhysicalMemory $memoryGB = $memory / 1 GB # raw result in bytes $memoryGB # rounding [ Int ] $memoryGB...
    • 16 Dec 2016

    Creating Time Spans

    You can use New-TimeSpan to define “amounts” of time, and then add or subtract them from dates. Here is an example: $1Day = New-TimeSpan -Days 1 $today = Get-Date $yesterday = $today - $1Day $yesterday A much easier way uses the built-in methods for DateTime objects: $today = Get-Date $yesterday = $today . AddDays ( - 1 ) $yesterday Also, you can use the TimeSpan .NET type to create...
    • 15 Dec 2016

    Waiting for Processes to Exit

    Sometimes, a PowerShell script needs to wait for external processes to finish. Here is what some users do: $processNameToWaitForExit = ' notepad ' do { Start-Sleep -Seconds 1 } while ( Get-Process -Name $processNameToWaitForExit -ErrorAction SilentlyContinue ) This approach is not ideal though because it waits at least for one second, even if the process is no longer running. Here is a better way: ...