Skip to content

Latest commit

 

History

History
467 lines (322 loc) · 20.7 KB

readme.md

File metadata and controls

467 lines (322 loc) · 20.7 KB

PowerShell Scripts

This repo contains my custom PowerShell profile scripts. It also contains scripts to automate the configuration of a new machine and installation of common apps and tools that I frequently use.

How to install

This entire repo can be overlayed ontop of your Documents\WindowsPowerShell folder.

As with all PowerShell scripts, you'll need to loosen up the execution policy on new machines.

Set-ExecutionPolicy RemoteSigned -Force -Confirm:$false;
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted -Force -Confirm:$false

Future: I'll consider signing the scripts and setting the execution policy to AllSigned.

If starting from scratch on a fresh machine:

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12';
$0 = 'https://raw.githubusercontent.com/stevencohn/WindowsPowerShell/main'
Invoke-WebRequest -Uri "$0/common.ps1" -OutFile C:\common.ps1;
Invoke-WebRequest -Uri "$0/Initialize-Machine.ps1" -OutFile C:\Initialize-Machine.ps1

Then execute Initialize-Machine:

. C:\Initialize-Machine.ps1 -Verbose

The script is re-entrant so can be run multiple times without a problem.

You can then delete these files since they exist in the Documents\WindowsPowerShell folder too:

rm C:\common.ps1 -Force;
rm C:\Initialize-Machine.ps1 -Force

Alternatives

Initialize-Machine downloads the repo to Documents\WindowsPowerShell. If you already have Git installed and would prefer to manually download the repo and run Initialize-Machine from there:

Set-Location $home\Documents;
git clone https://github.com/stevencohn/WindowsPowerShell.git

Or if you download the repo as a Zip file, you'll need to unblock all files after unzipping:

Get-ChildItem -Path "$home\Documents\WindowsPowerShell" -Recurse | Unblock-File

See also the other configuration scripts below.

Commands

These scripts are located in the Modules\Scripts folder.

Clear-Events [-Quiet]

Clear all events from the Windows Event Log.

Clear-Temp [-Quiet]

Clear the contents of TEMP, Windows\TEMP, and LocalAppData\TEMP.

Connect-AwsLogin [-Profile] [-Account] [-Device] [-Code]

Sign in to AWS CLI using MFA for the configured profile of an IAM user.

ConvertFrom-BinHex -Hex v -Unicode

Convert a BinHex encoded string back to its original string value.

Convert a Hex string into an integer value. If the string contains six or eight characters then it is also interpreted as an ARGB value and each component part is displayed.

ConvertTo-Hex -R r [-G g] [-B b]

Convert integer values to a Hex string. If one integer is specified then it is converted. If three integers are specified then they are assumed to be RGB values and combined into a single Hex string.

ConvertTo-mp3 -InputPath p [-Bitrate r] [-FullQuality] [-Info] [-Yes]

Primarily used to convert .m4a audio files to .mp3

Copy-Console [-OutFile f] [-All] [-Rtf] [-Trim]

Copy the contents of the Powershell console window preserving color. Can be sent to an out file or pasted into Word or OneNote.

Copy-Playlist -Playlist p -Target t -WhatIf

Copies all music files referenced by the given playlist to the specified location. For example, this can be used to copy music in an .m3u playlist file to a USB thumbdrive.

Open the hosts file in Notepad.

Enable-MultiRdp [-MaxConnection m]

Patch termsrv.dll to allow multiple concurrent RDP connections to this machine

Edit-Playlist -Replace r [-Path p] [-Type t]

Replace the path of all items in a playlist file to the current user's MyMusic path.

Run VSCode with ~Documents\WindowsPowerShell as root folder. Aliased to ep

Enable Personal OneDrive sync when both Business and Personal accounts are registered on the local machine. Will indicate when either is account not available.

Enable PowerShell remoting and trusted hosts for the current machine, typically run on a VM that will be used for automated tasks such as CI/CD.

Get-Account -Username u [-Domain d] [-SID] [-All]

Report the account information for the given username and optionally a specified domain.

alt text

Display a colorized directory listing along with total size. Aliased to ls

alt text

Get-Colors [-All] [-Cmd] [-PS] [-ConEmu] [-Script]

Display the console colors for Command console, PowerShell console, and ConEmu consoles.

alt text

Get-CommandLine [-Name n] [-Only] [-ReturnValue] [-ShowSystem]

Report processes with their command lines, highlighting an optional search string

Get-Commits -Project p [-Branch b] [-Since yyyy-mm-dd] [-Last n] [-Raw] [-Graph]

Reports all commits for the given git repo after a specified date or within the last n days.

Get-DirSize -Dir d [-la]

Report the size of all items in the specified folder. Used as a sub-routine of Get-ChildItemColorized.

Get the versions of.NET Framework installations on the local computer.

Get-Env [-Name n] [-Value v]

Report environment variables in colorized categoties with optional search highlighting.

alt text

Display the /etc/hosts file, colorized.

Get-Installed [-Store -Outfile f]

Report all installed applications registered on the local system, optionally including Store apps.

Get-Network [-Preferred] [-Addresses] [-WiFi] [-Verbose]

Determines the most likely candidate for the active Internet-specific network adapter on this machine. All other adpaters such as tunneling and loopbacks are ignored. Only connected IP adapters are considered. Wifi aliases are shown.

alt text

Determine the name of the nearest parent branch of the current branch in the local Git repo.

Get-Path [-Search s] [-Sort] [-Verbose]

Display the PATH environment variable as a list of strings rather than a single string and displays the source of each value defined in the Registry: Machine, User, or Process. Verbose mode dumps the User and System Paths as stored in the Windows Registry.

alt text

Get and report performance metrics using the built-in WinSAT utility.

Get-Reboots [-Uptime]

List Windows Event Log events related to system reboots.

List all external scripts and their parameter names.

Get-Services [-Name n] [-Running || -Stopped]

Get a list of services ordered by status and name. Aliased to gs

Get-SpecialFolder [-Folder f] [-All]

Return the translation of a SpecialFolder by name or show all SpecialFolders with optional search highlighting.

Get-VMConfig -Path p [-Json]

Returns a VM configuration object of the specified .vmcx VM configuration file even if the VM is not attached to a Hyper-V server.

Install-BuildTools [-Force] [-Full] [-VsWhere]

Install minimal Microsoft build and test tools required for CI/CD.

Can be used on new machines to install Chocolately. If already installed then checks if it is outdated and prompts to update.

Installs Docker for Windows, enabling Hyper-V as a prerequisite if not already installed.

Execute a given command as a non-evelated context. Aliased to nu. Convenient when you need to run as a normal user from an elevated prompt.

Open a new command prompt in elevated mode. Aliased to su. Special command for ConEmu emulator.

New-Administrator -Username -Password

Create a new local admin user.

Sepcial internal function from PowerShell Cookbook.

New-DriveMapping -DriveLetter d -Path p [-SourceDriveLabel s] [-DriveLabel l] [-Reboot] [-Force]

Create a persistent mapping of a folder to a new drive letter. (persistent SUBST)

New-Host -IP a -Name n

Adds or updates an entry in the Windows hosts file

New-RunAsShortcut -LinkPath l -TargetPath t [-Arguments a]

Creates a new elevated shortcut (.lnk file) to a given target

New-VMClone -Name n -Path p -Template t [-Checkpoint]

Create a new VM from a registered VM or an exported VM.

PrettyPrint-File -Path p [-Dedent] [-Overwrite]

Format or pretty-pretty JSON and XML files.

Prune unused docker containers and dangling images.

Remove-DriveMapping -DriveLetter d [-SourceDriveLabel s] [-Reboot] [-Force]

Remove a persistent mapping of a folder created by New-DriveMapping.

Remove a System-owned file or directory. Attempts multiple approaches to remove stubborn items.

Clean up the PATH environment variable, removing duplicates, empty values, invalid paths, repairs variable substitutions, and moves paths between User and System paths appropriately. Verbose mode dumps the User and System Paths as stored in the Windows Registry.

Restart-App -Name [-Command [-Arguments]] [-Register] [-GetCommand]

Restart the named process. This can be used to restart applications such as Outlook on a nightly basis. Apps such as this tend to have memory leaks or become unstable over time when dealing with huge amounts of data on a very active system. The -Register switch creates a nightly automation task.

Restarts the Bluetooth radio device on the current machine. This is useful when the radio stops communicating with a device such as a mouse. The alternative would be to reboot the system.

Set-Colors -Theme t | [-Name n -Color c [-Bgr] [-Background] [-Foreground]] [-Cmd] [-ConEmu] [-PS]

Set the color theme for command line consoles or set a specific named color.

Set-ItemOwner -Path p [-Group g]

Set the ownership of an item - folder or file - to the specified user group.

(Internal) Helper function for Get-ChildItemColorized.

Set-PinTaskbar -Target t [-Unpin]

Pins or unpins a target item to the Windows Taskbar (currently broken!)

Set-RegistryOwner -Hive h -Key k [-Recurse]

Set full-access ownership of a specified Registry key.

Set-SleepSchedule (-SleepTime -WakeTime) | (-Clear [-ClearTimers])

Creates scheduled tasks to sleep and wake the computer at specified times.

Invoke the Visual Studio environment batch script. Aliased to vs

Show-ColorizedContent -Filename f [-ExcludeLineNumbers]

Type the contents of a PowerShell script with syntax highlighting.

alt text

Show-Docker [-Ps] [-Containers] [-Images] [-Volumes]

Show containers and images in a single command.

alt text

Test-Elevated [-Action a ] [-Warn]

Determine if the current session is elevated and displays a warning message if not. Can be run without the warning message and simply return a boolean result.

Check the pending reboot status of the local computer.

Upgrades all outdated chocolatey packages, including Windows Terminal from a Windows Terminal.

Refresh the current session environment variables from the Registry by harvesting from both the local machine and the current user hives.

Update-Gits [-Branch b] [-Project p] [-Reset]

Scan all sub-folders looking for .git directories and fetch/pull each to get latest code.

Quick command line to pull latest source of this WindowsPowerShell repo from Github and update the content in $home\Documents\WindowsPowerShell.

WaitFor-VM -Name n [-Restore]

Start the named VM, optionally restoring the latest snapshot, and waiting until the OS provides a stable heartbeat.

Machine Setup and Configuration

Using the scripts below, a new machine can be configured and apps installed in under 30 minutes.

Run Set-ExecutionPolicy RemoteSigned prior to running if this is the first use of PowerShell.

The recommended sequence to run:

  1. Initialize-Machine.ps1
  2. Install-HyperV.ps1 (will reboot)
  3. Install-Programs.ps1 (might reboot)
  4. Install-Programs.ps1 -Developer -Extras
  5. Install-VS.ps1
  6. Install-VS.ps1 -Extensions
  7. Install-VS.ps1 -Code

This is a top-level script meant to be downloaded independently from this repo and run to configure and initialize new machines. This script will download this repo to the current user's Document folder, setting it up as the default PowerShell profile. Best to download it to and run from the root of C.

`Initialize-Machine.ps1 [-Command c] [-ListCommands]

  • command - optional argument to run a single command, default is to run all commands
  • -ListCommands - display all available commands supported by this script

The Initialize-Machine script will download this repo into the MyDocuments folder, but if you have OneDrive enabled then the MyDocuments folder may differ from $home\Documents. So before initializing, you can create a junction point to MyDocuments using this command:

  1. cd $home\Documents
  2. cmd /c "mklink /j WindowsPowerShell $([Environment]::GetFolderPath('MyDocuments'))\WindowsPowerShell"

Note there are two Initialie-Machine commands that are not run by default: DisableCortana and DisableOneDrive. To disable either of these, use the -Command argument, e.g.

.\Initialize-Machine.ps1 -Command DisableCortana

And since this updates the PowerShell console colors, you can close and reopen the console to appreciate these fantastic new colors.

Automates the installation of Hyper-V on Windows 11 for either Professional or Home editions. The script doesn't require any parameters but will prompt to reboot the computer to complete the configuration.

Automates the installation of applications, development tools, and other utilities. It's reentrant, skipping items already installed and installing items missing.

.\Install-Programs.ps1 [-Command c] [-ListCommands] [-Developer] [-Extras] [-Verbose]

  • command - optional argument to run a single command, default is to run all commands
  • -ListCommands - display all available commands supported by this script
  • -Developer - install developer-specific tools and apps
  • -Extras - install extra utilities and apps
  • -Vebose - print extra information for each command

Hyper-V is required for a couple of command and warning will be displayed if it is not yet available. Use Install-HyperV.ps1 to enable Hyper-V prior to running Install-Programs.

For Visual Studio and VSCode, use Install-VS.ps1.

Base applications:

  • Adobe Reader
  • BareTail Free (installed to C:\tools)
  • Greenshot
  • Macrium Reflect Free (downloads installer to be run manually)
  • mRemoteNG
  • Notepad++
  • SharpKeys
  • SysInternals procexp and procmon
  • Windows Terminal (for Win10 machines)

Developer applications:

  • .NET 6 SDK
  • Node.js (specific version)
  • Angular (specific version)
  • AWSCli
  • Docker Desktop
  • k9s
  • LINQPad
  • Nuget command line
  • Robot3T
  • S3Browser

Extra applications:

  • Audacity audio editor
  • DateInTray (installed to C:\tools; Win10 only)
  • Dopamine music player
  • Greenfish Icon Editor Pro
  • licecap
  • Paint.net
  • TreeSize Free
  • VLC
  • WiLMa (installed to C:\tools)
  • WmiExplorer (installed to C:\tools)

During the installation, hints and tips are shown highlighted in yellow and instructions are highlighted in cyan. Some are import, such as how to continue the manual installation of Macrium.

Reminders shown after a full install

Macrium Reflect

  1. Double-click the Macrium Installer icon on the desktop after VS is installed
  2. Choose Free on first screen, then Home version, and no registration is necessary

Consider these manually installed apps:

Standalone script to install Visual Studio and its extensions or VSCode and its extensions. The default is to install VS Professional.

.\Install-VS.ps1 [-Code|Community|Professional|Enterprise|Extensions] [-Verbose]

  • Visual Studio 2019 and extensions (professional or enterpise)
  • VSCode and extensions

When installing VS, let it complete and then rerun this script with the -Extensions parameter to install common extensions.

When installing VSCode (-Code), it will include extensions; there is no second step to do this.

Profiles

Microsoft.PowerShell_profile.ps1

This the primary PowerShell profile definition script, run whenenver a new PowerShell command prompt is open or session is created. It defines aliases for some of the commands above. It also invokes special utilities unique to my environment such as integration with ConEmu, WiLMa, Chocolatey, and setting the intial working directory.

Console Prompt Customization

The PowerShell command prompt is customized as follows:

  • It is rendered in blue
  • It indicates the current working directory prefaced with "PS" for example PS D:\code>
  • If the console is elevated then the "PS" prefix is shown in red to highlight the fact that what do you, you do at your own risk!

alt text

Microsoft.PowerShellISE_profile.ps1

This is the profile definition script fort the PowerShell ISE editor. It registers ISE add-ons found in the Modules\Addons folder.

Microsoft.VSCode_profile.ps1

This is the profile definition script for the VSCode integrated PowerShell terminal. It simply invokes the primary profile script above.

Dark Selenitic Scheme

The Dark Selenitic.StorableColorTheme.ps1xml file defines the Dark Selenitic color scheme for ISE. The theme is also defined by the Themes\PSTheme_Selenitic.ps1 script.