Powershell – Reboot and Continue Script

There is a great article on TechNet from the Hey, Scripting Guy series that goes over a situation very similar to what you are describing: Renaming a computer and resuming the script after reboot. The magic is to use the new workflows that are part of version 3: workflow Rename-And-Reboot { param ([string]$Name) Rename-Computer -NewName … Read more

Hashtables and key order

There is no built-in solution in PowerShell V1 / V2. You will want to use the .NET System.Collections.Specialized.OrderedDictionary: $order = New-Object System.Collections.Specialized.OrderedDictionary $order.Add(“Switzerland”, “Bern”) $order.Add(“Spain”, “Madrid”) $order.Add(“Italy”, “Rome”) $order.Add(“Germany”, “Berlin”) PS> $order Name Value —- —– Switzerland Bern Spain Madrid Italy Rome Germany Berlin In PowerShell V3 you can cast to [ordered]: PS> [ordered]@{“Switzerland”=”Bern”; “Spain”=”Madrid”; … Read more

How to get N files in a directory order by last modified date?

Limit just some files => pipe to Select-Object -first 10 Order in descending mode => pipe to Sort-Object LastWriteTime -Descending Do not list directory => pipe to Where-Object { -not $_.PsIsContainer } So to combine them together, here an example which reads all files from D:\Temp, sort them by LastWriteTime descending and select only the … Read more

Stop Powershell from exiting

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post. One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit “C:\SomeFolder\SomeScript.ps1” Per-script Fix: Add a prompt for input to the end … Read more

relative path in Import-Module

When you use a relative path, it is based off the currently location (obtained via Get-Location) and not the location of the script. Try this instead: $ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path Import-Module $ScriptDir\..\MasterScript\Script.ps1 In PowerShell v3, you can use the automatic variable $PSScriptRoot in scripts to simplify this to: # PowerShell v3 or higher #requires … Read more