In a previous post, I touched on some basic information regarding setting up a “profile” (startup) script in PowerShell.  Here I will expand a bit further and provide a full sample profile script.  For the uninitiated, a profile script is simply a script that executes automatically when you start up a Windows PowerShell instance. It’s worth noting that there are actually four possible files that can be used as profile scripts, each with a different scope.

Here’s an excerpt from PowerShell showing the four possible $profile script locations and usage (type “help about_profiles” for the whole thing):

 ...For example, the $Profile variable has the following values in the Windows PowerShell console     Name                               Description     -----------                        -----------     $Profile                           Current User,Current Host     $Profile.CurrentUserCurrentHost    Current User,Current Host     $Profile.CurrentUserAllHosts       Current User,All Hosts     $Profile.AllUsersCurrentHost       All Users, Current Host     $Profile.AllUsersAllHosts          All Users, All Hosts 

You can obtain the specific list for your PowerShell environment by pipe-lining the $profile object through the get-member cmdlet as follows:

 $profile | get-member -view extended | format-table definition Definition ---------- System.String AllUsersAllHosts=C:\Windows\System32\WindowsPowerShell\v2.0\profile.ps1 System.String AllUsersCurrentHost=C:\Windows\System32\WindowsPowerShell\v2.0\Microsoft.PowerShell_profile.ps1 System.String CurrentUserAllHosts=C:\Users\kahuna\Documents\WindowsPowerShell\profile.ps1 System.String CurrentUserCurrentHost=C:\Users\kahuna\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 

As you can see, there are multiple possibilities here and ways to setup a “master” profile that will affect all users who logon to a given host using the “$Profile.AllUsersCurrentHost” setting. One thing to be aware of, if you do use multiple profiles, make sure you don’t have any conflicting settings. For example, if you define the same alias in two profiles, the second profile will throw an error about  the alias already being defined.

Another thing worth noting, is that you can use the profile script to create in-memory functions that can be used anywhere within your powershell session, be it from the command-line or within a script.


Moving right along, here’s a sample profile script that I personally use. Since I’m typically jumping around between a lot of computers, I found it useful to add some output (write-host) commands to remind me of what functions are being defined in the profile script.

In this example, I carry out the following tasks:

  1. Set my current location to “c:\powershell”
  2. Define a “split-path” function and create an alias “path” command to invoke
  3. Define a “Get-Local-Disk” WMI function and create an alias “gld” command to invoke it
  4. Define a “CountDown” function and create an alias “cntdn” command to invoke it
  5. Finally, I display to the console (as a reminder) that the three functions have been defined – this is done in an alternate font color to help get my attention

Sample Profile Script:

?View Code POWERSHELL
write-host "Running Local Profile...." -backgroundcolor black -foregroundcolor Magenta -nonewline
set-location c:\powershell | out-null
 
function split-path {
  $p = @(get-content env:path|% {$_.split(";")})
  "Path"
  "===="
  foreach ($p1 in $p){
    if ($p1.trim() -gt ""){
      $i+=1;
      "$i : $p1"
      }
    }
  ""
  }
new-item -path alias:path -value split-path |out-null
 
function Get-LocalDisk{
  if ($args.count) {$hostname = $args[0]}
  else {$hostname = "localhost"}
  "***************************************************************"
  "*** $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($waitMinutes) {
    $startTime = get-date
    $endTime   = $startTime.addMinutes($waitMinutes)
    $timeSpan = new-timespan $startTime $endTime
    write-host "`nSleeping for $waitMinutes minutes..." -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
write-host "done" -backgroundcolor black -foregroundcolor green
 
write-host "Function: `"split-path`"    (alias: path  ) defined" -backgroundcolor black -foregroundcolor yellow
write-host "Function: `"Get-LocalDisk`" (alias: gld   ) defined" -backgroundcolor black -foregroundcolor yellow
write-host "Function: `"CountDown`"     (alias: CntDn ) defined" -backgroundcolor black -foregroundcolor yellow
write-host ""

 

 

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2011 Posh TipsSuffusion theme by Sayontan Sinha

Page optimized by WP Minify WordPress Plugin