Here’s a Powershell profile (startup script) that I use on several machines on a daily basis. If you use Powershell to any significant extent, I highly recommend customizing your environment to utilize a profile script.
I depend on this script SO MUCH! The script itself utilizes a script template that I developed which has some built-in features such as use of standard parameters -HELP (shows usage notes) and -HISTORY (which shows all of my maintenance notes). In addition, the script will automatically display a banner with some identifying information AND the most recent maintenance date. This maintenance date is important as that is what I use as a “version” identifier; if I start a Powershell session on a machine lacking the latest version, it will be evident by a quick glance to the displayed banner.
Ok, enough of that… let’s get on to what the script actually does…
Here are some of the features:
- Working Directory
Sets a default working (scripts) directory (will create the directory if it is not already there) - Define Functions
Defines a handful of frequently-used functions and sets short-cut aliases - list-profiles (alias: lpro)
Display all of the possible profile locations and tells whether or not a file actually exists in each spot.
$profile.AllUsersAllHosts
$profile.AllUsersCurrentHost
$profile.CurrentUserAllHosts
$profile.CurrentUserCurrentHost - split-envpath (alias: epath)
Splits all of the semi-colon delimited environment PATH items and presents in a list format. - Get-LocalDisk (alias: gld)
Get a quick human-readable view of your local disks. Details include DeviceId, Name, FreeSpace, and Capactiy. Disk details are presented in Gigabytes (much easier to read than default bytes view). - CountDown (alias: CntDn)
This is the Countdown timer posted elsewhere on this site; I use this when doing some command-line adhoc query of a remote system that needs to repeat periodically; e.g. waiting for “something” to happen. - NewTimeStampedFile (alias: ntf)
Also posted elsewhere on this site, I use NTF quite a bit where I need to write unique log files. - Credential Functions
Folks, these two jewels are THE BOMB and fantastic for working with multiple accounts or background tasks where you need to specify credentials. The beauty here is that the credential are encrypted. And you are not just limited to Windows Domain or Host access! I use these functions to access my AWS (Amazon Web Services) S3 account data. - Export-Credentail (alias: ecred)
Save credentials to a file - Import-Credential (alias: icred)
Read the stored credentials file - get-command (alias: which)
This is the Powershell built-in command; I’m just used to the UNIX “which” command which is very similar - Setup Aliases to executable programs
This really saves me a LOT OF TIME. When I need to pull up a text editor or MS excel, I can do so quickly from the powershell command-line instead of mousing around for it. I’ve built a framework here that checks if a given program path is valid before creating an alias and it is structured so that adding more applications is a breeze. I have even built in support for x86/x64 system differences so that the script will search for the application’s presence in multiple locations before creating the alias. - Notepad++ (alias: npp)
My favorite text editor! - Excel (alias: excel [how imaginative!])
Great for csv files - Open Office Spreadsheet (alias: oo3)
I use this on systems that I don’t want/need to license a copy of Excel (ok for small spreadsheets but really sucks if you’re an excel power-user)
So there you have it – if you find this half as useful as I do, it will be a keeper and used in your Powershell environment.
If you are brand-new to Powershell and do not already have a profile script, here’s a quick jumpstart for you:
Download the profile script on this site to your local machine (e.g. to c:\temp\myProfile.ps1)
You may have to “unblock” the script before powershell will actually let you use it. To do this, access the script via Windows Explorer, right-click on the file, select properties, click on the “unblock” button, and click “apply”.
open a powershell command window and do the following commands
if (!(test-path $profile.CurrentUserCurrentHost)){new-item $profile.CurrentUserCurrentHost -type file}
copy MyProfile.ps1 $profile.CurrentUserCurrentHost
set-executionpolicy unrestricted -force
Finally, close your PowerShell session and start up a new one.
You should see something similar to this:
Finally, here the script
Download Link : MyProfile.ps1 (right-click and select save as…)
Or cut-and-paste from the listing below
ENJOY!
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
Param ([switch]$help,[switch]$history) $HelpText = @' ####################################################################################### Script : {0} Title : PoshTips Startup Profile Script Date : (see maintenace log below) Author : xb90@poshtips.com Purpose : Use this setup commonly used functions, scripts dir, aliases, etc Disclaimer : This script carries no warranty either expressed or implied regarding suitability for use in your computing environment. PoshTips.com highly recommends thorough testing of this script before using it in a production environment. Users of this script assume all risk for any undesireable results. Usage: Script runs automatically once installed to your preferred $profile path Optional Params: -Help show this help page -History show this help page + maintenance history ####################################################################################### '@ $HistoryText = @' Maintenance Log Date By Updates (important: insert newest updates at top) ---------- ---- --------------------------------------------------------------------- 03/18/2012 KES Dynamically insert $profile script name 03/14/2012 KES Auto-create scripts directory if does not exist; header update 09/29/2011 KES Added Alias for shortcuts to open office 3 08/23/2011 KES Added Aliases for shortcuts to notepad++ and excel 08/01/2011 KES New Script ####################################################################################### '@ $myScriptsDir = "$($env:SystemDrive)\scripts\powershell" $myProfileScript = $MyInvocation.MyCommand.Path switch ($myProfileScript) { $profile.AllUsersAllHosts {$myProfileScript = "`$profile.AllUsersAllHosts"} $profile.AllUsersCurrentHost {$myProfileScript = "`$profile.AllUsersCurrentHost"} $profile.CurrentUserAllHosts {$myProfileScript = "`$profile.CurrentUserAllHosts"} $profile.CurrentUserCurrentHost {$myProfileScript = "`$profile.CurrentUserCurrentHost"} } function ShowHeader { $h = @() $h += $HelpText |% {($_.split("`n")[1].trim() -f $MyProfileScript )} $h += $HelpText |% {$_.split("`n")[2].trim()} $h += $HelpText |% {$_.split("`n")[4].trim()} $lmdte = $HistoryText |% {$_.split("`n")[3].split(" ")[1].trim()} $h += ("Last Updated : {0}" -f $lmdte) foreach ($x in $h) { write-host $x.padright(80) -back cyan -fore black } write-host "" } function CheckArgs { if ($help -or $History){ write-host $HelpText if ($History){write-host $HistoryText} exit } } function list-profiles { #use to quickly check which (if any) profile slots are inuse $profile|gm *Host*| ` % {$_.name}| ` % {$p=@{}; ` $p.name=$_; ` $p.path=$profile.$_; ` $p.exists=(test-path $profile.$_); new-object psobject -property $p} | ft -auto } new-item -path alias:LPro -value list-profiles | out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function split-envpath { #display system path components in a human-readable format $p = @(get-content env:path|% {$_.split(";")}) "Path" "====" foreach ($p1 in $p){ if ($p1.trim() -gt ""){ $i+=1; "$i : $p1" } } "" } new-item -path alias:epath -value split-envpath |out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Get-LocalDisk{ Param ([string] $hostname="localhost") #Quick Local Disk check "***************************************************************" "*** $hostname : Local Disk Info" Get-WmiObject ` -computer $hostname ` -query "SELECT * from Win32_LogicalDisk WHERE DriveType=3" ` | format-table -autosize ` DeviceId, ` VolumeName, ` @{Label="FreeSpace(GB)"; Alignment="right"; Expression={"{0:N2}" -f ($_.FreeSpace/1GB)}},` @{Label="Size(GB)"; Alignment="right"; Expression={"{0:N2}" -f ($_.size/1GB)}} ` | out-default } new-item -path alias:gld -value Get-LocalDisk |out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function CountDown() { param( [int]$hours=0, [int]$minutes=0, [int]$seconds=0, [switch]$help) $HelpInfo = @' Function : CountDown By : xb90 at http://poshtips.com Date : 02/22/2011 Purpose : Pauses a script for the specified period of time and displays a count-down timer to indicate the time remaining. Usage : Countdown [-Help][-hours n][-minutes n][seconds n] where -Help displays this help -Hours n specify the number of hours (default=0) -Minutes n specify the number of minutes (default=0) -Seconds n specify the number of seconds (default=0) '@ if ($help -or (!$hours -and !$minutes -and !$seconds)){ write-host $HelpInfo return } $startTime = get-date $endTime = $startTime.addHours($hours) $endTime = $endTime.addMinutes($minutes) $endTime = $endTime.addSeconds($seconds) $timeSpan = new-timespan $startTime $endTime write-host $([string]::format("`nScript paused for {0:#0}:{1:00}:{2:00}",$hours,$minutes,$seconds)) -backgroundcolor black -foregroundcolor yellow while ($timeSpan -gt 0) { $timeSpan = new-timespan $(get-date) $endTime write-host "`r".padright(40," ") -nonewline write-host "`r" -nonewline write-host $([string]::Format("`rTime Remaining: {0:d2}:{1:d2}:{2:d2}", ` $timeSpan.hours, ` $timeSpan.minutes, ` $timeSpan.seconds)) ` -nonewline -backgroundcolor black -foregroundcolor yellow sleep 1 } write-host "" } new-item -path alias:CntDn -value CountDown |out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function NewTimestampedFile() { Param ( [string]$Folder="", [string]$Prefix="temp", [string]$Type="log", [switch]$Help ) $HelpInfo = @' Function : NewTimestampedFile By : xb90 at http://poshtips.com Date : 02/23/2011 Purpose : Creates a unique timestamp-signature text file. Usage : NewTempFile [-Help][-folder ][-prefix ][-type ] where -Help displays this help -Folder specify a subfolder or complete path where the new file will be created -Prefix a text string that will be used as the the new file prefix (default=TEMP) -Type the filetype to use (default=LOG) Details : This function will create a new file and any folder (if specified) and return the name of the file. If no parameters are passed, a default file will be created in the current directory. Example: temp_20110223-164621-0882.log '@ if ($help){ write-host $HelpInfo return } #create the folder (if needed) if it does not already exist if ($folder -ne "") { if (!(test-path $folder)) { write-host "creating new folder `"$folder`"..." -back black -fore yellow new-item $folder -type directory | out-null } if (!($folder.endswith("\"))) { $folder += "\" } } #generate a unique file name (with path included) $x = get-date $TempFile=[string]::format("{0}_{1}{2:d2}{3:d2}-{4:d2}{5:d2}{6:d2}-{7:d4}.{8}", $Prefix, $x.year,$x.month,$x.day,$x.hour,$x.minute,$x.second,$x.millisecond, $Type) $TempFilePath=[string]::format("{0}{1}",$folder,$TempFile) #create the new file if (!(test-path $TempFilePath)) { new-item -path $TempFilePath -type file | out-null } else { throw "File `"$TempFilePath`" Already Exists!" } return $TempFilePath } new-item -path alias:ntf -value NewTimestampedFile |out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Export-PSCredential { param ( #$Credential = (Get-Credential), $Credential = "", $Path = "credentials.enc.xml", [switch]$Help) $HelpInfo = @' Function : Export-PSCredential Date : 02/24/2011 Purpose : Exports user credentials to an encoded XML file. Resulting file can be imported using function: Import-PSCredential Usage : Export-PSCredential [-Credential ][-Path ][-Help] where -Credential specify the user account for which we will create a credential file password will be collected interactively -Path specify the file to which credential information will be written. if omitted, the file will be "credentials.enc.xml" in the current working directory. -Help displays this help information Note : Import-PSCredential can be used to decode this file into a PSCredential object and MUST BE executed using the same user account that was used to create the encoded file. '@ if ($help){ write-host $HelpInfo return } $Credential = (Get-Credential $credential) # Look at the object type of the $Credential parameter to determine how to handle it switch ( $Credential.GetType().Name ) { # It is a credential, so continue PSCredential { continue } # It is a string, so use that as the username and prompt for the password String { $Credential = Get-Credential -credential $Credential } # In all other caess, throw an error and exit default { Throw "You must specify a credential object to export to disk." } } # Create temporary object to be serialized to disk $export = "" | Select-Object Username, EncryptedPassword # Give object a type name which can be identified later $export.PSObject.TypeNames.Insert(0,’ExportedPSCredential’) $export.Username = $Credential.Username # Encrypt SecureString password using Data Protection API # Only the current user account can decrypt this cipher $export.EncryptedPassword = $Credential.Password | ConvertFrom-SecureString # Export using the Export-Clixml cmdlet $export | Export-Clixml $Path Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine # Return FileInfo object referring to saved credentials Get-Item $Path } new-item -path alias:ecred -value Export-PSCredential |out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Import-PSCredential { param ( $Path = "credentials.enc.xml", [switch]$Help) $HelpInfo = @' Function : Import-PSCredential Date : 02/24/2011 Purpose : Imports user credentials from an encoded XML file. Usage : $cred = Import-PSCredential [-Path ][-Help] where $cred will contain a PSCredential object upon successful completion -Path specify the file from which credentials will be read if omitted, the file will be "credentials.enc.xml" in the current working directory. -Help displays this help information Note : Credentials can only be decoded by the same user account that was used to create the encoded XML file '@ if ($help){ write-host $HelpInfo return } # Import credential file $import = Import-Clixml $Path # Test for valid import if ( !$import.UserName -or !$import.EncryptedPassword ) { Throw "Input is not a valid ExportedPSCredential object, exiting." } $Username = $import.Username # Decrypt the password and store as a SecureString object for safekeeping $SecurePass = $import.EncryptedPassword | ConvertTo-SecureString # Build the new credential object $Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass Write-Output $Credential } new-item -path alias:icred -value Import-PSCredential |out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ New-Alias which get-command ShowHeader if (!(test-path $myScriptsDir)){ write-host "creating default scripts directory ($myScriptsDir)" -back black -fore green new-item -path $myScriptsDir -type directory } set-location $myScriptsDir | out-null # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ write-host "** New Declarations **".padright(50) -back black -fore yellow write-host "Type Name Alias".padright(50) -back yellow -fore black write-host "Function list-profiles lpro ".padright(50) -back black -fore yellow write-host "Function split-envpath epath ".padright(50) -back black -fore yellow write-host "Function Get-LocalDisk gld ".padright(50) -back black -fore yellow write-host "Function CountDown CntDn".padright(50) -back black -fore yellow write-host "Function NewTimestampedFile ntf ".padright(50) -back black -fore yellow write-host "Function Export-PSCredential ecred".padright(50) -back black -fore yellow write-host "Function Import-PSCredential icred".padright(50) -back black -fore yellow write-host "CmdLet Get-Command which".padright(50) -back black -fore yellow write-host "" # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ $PgmAliasList = ( "npp |c:\program files\notepad++\notepad++.exe; ` c:\program files (x86)\notepad++\notepad++.exe", "excel |C:\Program Files\Microsoft Office\Office12\EXCEL.EXE", "oo3 |C:\Program Files (x86)\OpenOffice.org 3\program\soffice.exe; ` C:\Program Files\OpenOffice.org 3\program\soffice.exe" ) write-host "Setting up Program Aliases...`n" -background black -foreground green write-host " Alias Path" write-host " ========== =======================================" foreach ($alias in $PgmAliasList) { $name = $alias.split("|")[0].trim() write-host " $($name.padright(12))" -nonewline if (!(test-path Alias:\$name)){ $pgmPaths = $alias.split("|")[1].split(";") $pathOk = $false foreach ($pgmPath in $pgmPaths) { if (test-path $pgmPath.trim()){ set-alias $name $pgmPath.trim() -scope Global write-host $pgmPath.trim() -background black -foreground green $pathOk = $true break } } if (!$pathOk) { write-host "No valid path found" -background black -foreground red } } else { $x = get-alias $name write-host "Already defined ($($x.definition))" -background black -foreground yellow } } write-host "" |

This has been really useful for me! Thank you for putting such a comprehensive description. Can I ask; is there a cmdlet that shows all the functions in a user profile, I see you entered the details manually using write-host? I cant seem to find one in help/online so i assume not? Thanks! Chris
Hey Chris,
Glad you find this to be useful. I’m not aware of any cmdlet that is capable of listing the functions defined in the user profile – that’s sort of what led me to list them out as part of the profile’s execution.
Thanks for visiting!
-xb90