Here is a one-liner that retrieves your original Windows product key:
(Get-WmiObject -Class "SoftwareLicensingService").OA3xOriginalProductKey
psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want…
In the previous tip we explained how PowerShell can send PDF documents to the default PDF printer. This generic approach is OK for simple scenarios but won’t let you choose a specific printer.
You get more control when you use a specific software because then you can use specific features exposed by that software.
The example below uses Acrobat Reader to print out PDF documents. It shows how you can use the specific…
To automatically print PDF documents, unfortunately you cannot use Out-Printer. Out-Printer can only send pure text documents to a printer.
However, take a look at this line:
# adjust this path to the PDF document of choice
$Path = "c:\docs\document.pdf"
Start-Process -FilePath $Path -Verb Print
Provided you have software installed that can print PDF document, this code sends the document to the associated…
Windows 10 comes with Windows Subsystem for Linux (WSL) feature that you can use to run various Linux distributions. Launch a PowerShell with elevated privileges to enable the WSL:
Enable-WindowsOptionalFeature -FeatureName Microsoft-Windows-Subsystem-Linux -Online
Next, open the Microsoft Store on Windows 10, and search for “Linux”. Install one of the supported Linux distros (for example, Debian)!
Here is a one-liner that returns the resolved name from the current user’s SID:
You may be arguing it is easier to query the environment variable $env:username for this, which is true. However, converting a SID to name can come handy in many scenarios. For example, if you must know the exact…
Here is a one-liner that returns the SID for the current user and can be used in logon scripts, for example:
psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there…
Here is a straightforward way to test ports on a local or remote system. You can even specify a timeout (in milliseconds):
$ComputerName = $env:COMPUTERNAME
# try and establish a connection to port…
It can be easy to mess up console colors in the PowerShell console. A single call with accidental values, or a script that messed with the colors, can lead to unexpected results. Check for yourself, open a PowerShell console (not an editor!), and run this:
PS> [Console]::BackgroundColor = "Green"
To quickly clean up colors, run this:
Run Clear-Host afterwards to…
Sometimes when you try to access web services (or download internet content in general), PowerShell may bail out and complain about not being able to set up a protected SSL channel.
Let’s take a look at such an issue. Below is a code that is calling a web service connected to the German railway system. It is supposed to list the train stations in a given city:
$city = "Hannover"
$url = "https://rit.bahn…
If you’re writing log activity to files, you may want to clean up things, so maybe you’d like to always delete the oldest log file when you add a new one.
Here is a simple approach:
# this is the folder keeping the log files
$LogFileDir = "c:\myLogFiles"
# find all log files...
Get-ChildItem -Path $LogFileDir -Filter *.log |
# sort by last change ascending
# (oldest first)...
Classic foreach loops are the fastest loop available but they come with a severe limitation. Foreach loops do not support streaming. You need to always wait for the entire foreach loop to finish before you can start processing the results.
Here are some example illustrating this. With the code below, you have to wait a long time until you “see” the results:
$result = foreach ($item in $elements)
There are many ways to create a list of network drives. One involves a COM interface that was used by VBScript as well, and we’ll pick it to illustrate a special PowerShell technique.
To dump all network drives, simply run these lines:
$obj = New-Object -ComObject WScript.Network
The result may look similar to this:
You can always use Send-MailMessage to send a mail via any SMTP server. If you’d like to use your Outlook client, though, i.e. to keep access to your address books, use your companies Exchange server, or save the mail in your mail history, here is a quick function that shows how:
Polishing raw text is not always trivial, and when you’d like to make sure names or texts are well-formed, and each word starts with a capital letter, it typically involves much work.
Funny enough, every CultureInfo object has a built-in ToTitleCase() method that does the job for you. If you convert the raw text to all lowercase before, it also takes care of all uppercase words:
$text = "here is some TEXT that I…
Let’s assume a script has written multiple log files in a folder, all with extension *.log. You would like to consolidate them into one big file. Here is a simple approach:
$OutPath = "$env:temp\summary.log"
Get-Content -Path "C:\Users\tobwe\Documents\ScriptOutput\*.log" |
Invoke-Item -Path $OutPath
However, this approach wouldn’t give a lot of control to you: all files…
Every Windows installation has a unique UUID that you can use to distinguish machines. While computer names can change, the UUID won’t:
PS> (Get-CimInstance -Class Win32_ComputerSystemProduct).UUID
In reality, the UUID is just a GUID (Globally Unique Identifier), which comes in different formats:
$uuid = (Get-CimInstance -Class Win32_ComputerSystemProduct).UUID
In the previous tip we illustrated how Get-Date can take a format string and convert DateTime values to strings. The string conversion always uses your local language though. That might not always be what you need. Let’s check out the problem, and a solution for it:
Here is an example outputting the weekday name for Christmas Eve in 2018:
$christmasEve = Get-Date -Date '2018-12-24'
Get-Date -Date $chri…
Formatting date and time to your needs is easy with the -Format parameter provided by Get-Date. You can use it either with the current date, or external DateTime variables. Simply use the wildcards for the date and time elements you want to convert to an output string.
Here are a couple of examples. To output the current date in ISO format, for example, run this:
PS> Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
In the previous tip we created the function Out-PDFFile which accepts any PowerShell results and turns them into a PDF file – using the built-in printer drivers in Windows 10 and Windows Server 2016.
We used a simple function for this to use the $Input automatic variable to easily access the piped data. If you’d rather like to use an advanced function to take advantage of mandatory parameters, we wrapped the project…
In the previous tip we explained how you can use PowerShell on Windows 10 and Windows Server 2016 to set up a PDF printer that prints anything to a PDF file, of course unattended. To make it really useful, let’s wrap it into a function called Out-PDFFile. Anything you pipe to this new command is turned into a PDF file.
Important: for this function to work, you must have set up the printer “PrintPDFUnattended” as…
In the previous tip we illustrated how you can use the built-in “Microsoft Print to PDF” printer to send PowerShell output to PDF files. However, this printer prompts you for an output file, so it is no good for automation tasks.
To avoid the file prompt, there is a little-known secret: simply assign the printer a port where you use the output file path as port name. Or in other words, run this script to create…
Windows 10 and Windows Server 2016 finally come with a built-in PDF printer called “Microsoft Print to PDF” that you can use from PowerShell to create PDF files. Run this to check your PDF printer:
$printer = Get-Printer -Name "Microsoft Print to PDF" -ErrorAction SilentlyContinue
Write-Warning "Your PDF Printer is not yet available!"
Write-Warning "PDF printer…
Windows 10 and Windows Server 2016 come with extensive printer support thanks to the PrintManagement module. If you’d like to print official test pages on your printers, though, you need to resort to WMI.
#requires -Version 3.0 -Modules CimCmdlets, PrintManagement
Out-GridView -Title 'Print test page on selected printers' -OutputMode Multiple |
In the previous tip we introduced the FileSystemWatcher and illustrated how it can miss filesystem changes when your handler code takes too long.
To use the FileSystemWatcher correctly, you should use it asynchronously and make sure it uses a queue. So even if your script is busy processing a filesystem change, it should continue to log new filesystem changes and process them once PowerShell is done processing previous…
A FileSystemWatcher can monitor a file or folder for changes, so your PowerShell code can immediately be notified when new files are copied to a folder, or when files are deleted or changed.
Often, you find example code for synchronous monitoring like this:
# make sure you adjust this
$PathToMonitor = "c:\test"
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $PathToM…