String Theory

Mastering the laws of physics with Windows PowerShell

Browsing Posts in User Groups

Date:

09/01/2010 (Wednesday)
Time: 11:00AM – 1:30PM EDT

Description:
The User Group
meetings provide members with an opportunity to share and learn about
common issues and utilization of Server Based Computing technology.
Additional segments include troubleshooting tips, best practices,
enterprise solutions, technology trends, vendor presentations and
upcoming activities of interest.

Agenda:
11:00am: Registration
11:15am: Opening Remarks and Organization News
11:30am: Citrix Announcements – Product Updates, Beta Announcements & Tech Releases
11:45am: Lunch
12:00pm: Citrix XenDesktop – Jonathan O’Brien, Citrix Systems
1:00pm: Open Discussion

Location:
Microsoft Southeast Regional Office – Alpharetta
1125 Sanctuary Pkwy., Suite 300
Alpharetta, GA 30009
Phone: (678) 629-5700

Registration: http://www.acug.org/index.php?view=details&id=2%3Aseptember-atlanta-citrix-user-group-meeting&option=com_eventlist&Itemid=53

For this month’s meeting of the Atlanta PowerShell User Group I demoed my Windows PowerShell profile and I promised I would post it online. So here it is.


 

 

<#=============================================================================
Script Name:     Universal Profile
Created On:      05/22/2009
Author:          Mark E. Schill
File:            profile.ps1
Usage:           PS> . profile.ps1
Version:         1.2
Purpose:         Serves as a PowerShell Profile that can be used on multiple systems
Requirements:    <NONE>
Last Updated:    06/05/2010
History:
         1.2 06/05/2010 - Many Numerous changes.
                 1.1 10/11/2009 - Converted to strictly 2.0 and updated layout
              1.0 05/22/2009 - Initial Revision

         ** Licensed under a Creative Commons Attribution 3.0 License **
=============================================================================#>

<# This must be configured on systems where this script is run
 New-PSDrive -name Scripts -psprovider FileSystem -root <Location of Scripts Folder> -Description "Scripts Folder"
 . Scripts:\Profiles\profile.ps1
#>

# Main Function is just like the C# Main function. I use it to be be able to put functions last.
function Main
{

  # Grab some system Information to be displayed
  $PSVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("$PSHome\Powershell.exe").FileVersion
  $IPAddress = @( Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.DefaultIpGateway } )[0].IPAddress[0]
  $Cert = Get-ChildItem -Path Cert:\CurrentUser\my -CodeSigningCert

    # Set up general aliases
  New-Alias -Name "Edit" -Value "edit-file" -force

  # Add to Module path so I can just do "ipmo Module"
  if ( !($Env:PSModulepath.Contains($(Convert-Path Scripts:\Core\Modules\Manual)) ))
  {    $env:PSMODULEPATH += ";" + $(Convert-Path Scripts:\Core\Modules\Manual) }

  # Import my auto modules.
  Get-ChildItem $(Convert-Path Scripts:\Core\Modules\Auto) | Where-Object {$_.PsIsContainer} | %{ Import-Module $($_.FullName) -Force }

  ## We also want to add our scripts directory to the path
  $ENV:PATH += Get-Item Scripts:\Core\Functions | ? { $_.PsIsContainer } | % {";$($_.FullName)" }
  $ENV:PATH += Get-ChildItem Scripts:\Core\Functions\* | ? { $_.PsIsContainer } | % {";$($_.FullName)" }

  # Machine Based Rules
  switch -regex ( $env:COMPUTERNAME)
  {
    ".+"
    {    }
    "L186404"
    {      Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue }
    "EINSTEIN"
    {
      Add-PSSnapin "NetCmdlets" -ErrorAction SilentlyContinue
      Add-PSSnapin "PowerGadgets" -ErrorAction SilentlyContinue
    }
  }

  # Host based rules
  switch ( $Host.Name )
  {
    "PowerShellPlus Host"
    {
      $Color_Label = "Cyan"
      $Color_Value_1 = "Green"
      $Color_Value_2 = "Yellow"
      $HostWidth = $Host.UI.RawUI.WindowSize.Width
    }
    'Windows PowerShell ISE Host'
    {
      $Color_Label = "DarkCyan"
      $Color_Value_1 = "Magenta"
      $Color_Value_2 = "DarkGreen"
      $HostWidth = 80

            Import-Module ISEPack 

            $PSISE.options.FontName = "Consolas"

      # watch for changes to the Files collection of the current Tab
      register-objectevent $psise.CurrentPowerShellTab.Files collectionchanged -action {
        # iterate ISEFile objects
        $event.sender | % {
          # set private field which holds default encoding to ASCII
          $_.gettype().getfield("encoding","nonpublic,instance").setvalue($_, [text.encoding]::ascii)
        }
      } | Out-null
    }
    default
    {
      $Color_Label = "Cyan"
      $Color_Value_1 = "Green"
      $Color_Value_2 = "Yellow"
      $HostWidth = $Host.UI.RawUI.WindowSize.Width

      if ( $env:PROCESSOR_ARCHITECTURE -eq 'AMD64')
      {        $NPP = "${env:ProgramFiles(x86)}\Notepad++\Notepad++.exe" }
      else
      {        $NPP = "$env:ProgramFiles\Notepad++\Notepad++.exe" }
      if (Test-Path $NPP) { Set-Alias -Name Edit-File -Value $NPP -Force } 

      # Initialize PowerTab
      & $(Convert-Path scripts:\Core\Includes\PowerTab\Init-TabExpansion.ps1) -ConfigurationLocation $(Convert-Path scripts:\Core\Includes\PowerTab)
    }

  }

  Record-Session # Start Session Recording
  Clear-Host

    $PreviousColor = $Host.UI.RawUI.ForegroundColor

  # Display relevant information
  Write-Host "ComputerName:`t`t" -ForegroundColor $Color_Label -nonewline
  Write-Host "$($env:COMPUTERNAME)" -ForegroundColor $Color_Value_2
  Write-Host "IP Address:`t`t" -ForeGroundColor $Color_Label -nonewline
  Write-Host $IPAddress -ForeGroundColor $Color_Value_2
  Write-Host "UserName:`t`t" -ForegroundColor $Color_Label -nonewline
  Write-Host "$env:UserDomain\$env:UserName" -ForegroundColor $Color_Value_2
  Write-Host "PowerShell Version:`t" -ForegroundColor $Color_Label -nonewline
  Write-Host $PSVersion -ForegroundColor $Color_Value_2
  Write-Host "Code Signing Cert:`t" -ForegroundColor $Color_Label -nonewline
  Write-Host $Cert.FriendlyName -ForegroundColor $Color_Value_2

  Write-Host "Snapins:`t`t" -ForegroundColor $Color_Label -NoNewline
  $StartingPosition = $Host.UI.RawUI.CursorPosition.X
  Write-Host "".PadRight(30,"-") -ForegroundColor $Color_Label
  Get-PSSnapin | Format-Wide -autosize | Out-String -Width $( $HostWidth -$StartingPosition -1 ) -stream | Where-Object {$_} | %{ Write-Host $($(" "*$StartingPosition) + $_) -foregroundColor $Color_Value_1} 

  Write-Host "Modules:`t`t" -foregroundcolor $Color_Label -noNewLine
  $StartingPosition = $Host.UI.RawUI.CursorPosition.X
  Write-Host "".PadRight(30,"-") -ForegroundColor $Color_Label

  Get-Module | Format-Wide -AutoSize | Out-String -Width $( $HostWidth -$StartingPosition -1 ) -stream | Where-Object {$_} |  %{ Write-Host $($(" "*$StartingPosition) + $_) -foregroundColor $Color_Value_1}
  Get-Module -ListAvailable | Format-Wide -Column 3 | Out-String -Width $( $HostWidth -$StartingPosition -1 ) -stream | Where-Object {$_} |  %{ Write-Host $($(" "*$StartingPosition) + $_) -foregroundColor $Color_Value_2} 

  Write-Host "Functions:`t`t" -foregroundcolor $Color_Label -noNewLine
  $StartingPosition = $Host.UI.RawUI.CursorPosition.X
  Write-Host "".PadRight(30,"-") -ForegroundColor $Color_Label
  Get-ChildItem Scripts:\Core\Functions\* -Recurse | Select-Object Name | Format-Wide -AutoSize | Out-String -Width $( $HostWidth -$StartingPosition -1 ) -stream | Where-Object {$_} |  %{ Write-Host $($(" "*$StartingPosition) + $_) -foregroundColor $Color_Value_1}  

  $Host.UI.RawUI.ForegroundColor =$PreviousColor
  Write-Host ""
  Write-Host ""

  # This should go OUTSIDE the prompt function, it doesn't need re-evaluation
    # We're going to calculate a prefix for the window title
  if(!$global:WindowTitlePrefix) {
    $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $p = New-Object System.Security.Principal.WindowsPrincipal($id)
    if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
    {
      $global:WindowTitlePrefix = "PoSh (ADMIN) -"
    } else {
      $global:WindowTitlePrefix = "PoSh - "
    }
  }

  $LogicalDisk = @()
  gwmi Win32_LogicalDisk -filter "DriveType='3'" | % {
    $LogicalDisk += @($_ | Select @{n="Name";e={$_.Caption}},
    @{n="Volume Label";e={$_.VolumeName}},
    @{n="Used (GB)";e={"{0:N2}" -f ( ($_.Size/1GB) - ($_.FreeSpace/1GB) )}},
    @{n="Free (GB)";e={"{0:N2}" -f ($_.FreeSpace/1GB)}},
    @{n="Size (GB)";e={"{0:N2}" -f ($_.Size/1GB)}},
    @{n="Free (%)";e={if($_.Size) { "{0:N2}" -f ( ($_.FreeSpace/1GB) / ($_.Size/1GB) * 100 )}else{"NAN"} }} )
  } 

  $Host.UI.RawUI.ForegroundColor = $Color_Value_2
  $LogicalDisk | format-table -AutoSize | out-string
  $Host.UI.RawUI.ForegroundColor = $PreviousColor

  Get-SystemUptime
  Write-Host

  cd scripts:\

}

#Record all Powershell activities
function Record-Session
 {
  $MyPath = "$((Get-PSDrive Scripts).Root)\_Transcripts"
  if ( ! (Test-Path $MyPath ) ) { mkdir $MyPath > $null }
  $ComputerName = $env:ComputerName
  $Date = Get-Date -Format "yyyy-MM-dd"
  switch ( $Host.Name )
  {
    "PowerShellPlus Host"
    {      Start-Transcript -path "$MyPath\$ComputerName-$Date.log" -ea silentlycontinue }
    'Windows PowerShell ISE Host'
        {
            # PowerShell ISE does not support transcription
        }
        default
    {      Start-Transcript -path "$MyPath\$ComputerName-$Date.log" -append -ea silentlycontinue }

  }
}

function prompt
{

  Write-Host "$([char]0x0A7) " -NoNewline -ForegroundColor $Color_Label
  Write-Host ([net.Dns]::GetHostName()) -NoNewline -ForegroundColor $Color_Value_1
  Write-Host ' {' -NoNewline -ForegroundColor "Red"
  Write-Host (shorten-path (pwd).path) -NoNewline -ForegroundColor $Color_Label
  Write-Host '}' -NoNewline -ForegroundColor "Red"
  return ' '
}


function shorten-path([string] $path) {
  $loc = $path.Replace($HOME, '~')
  # remove prefix for UNC paths
  $loc = $loc -replace '^[^:]+::', ''
  # make path shorter like tabs in Vim,
    # handle paths starting with \\ and . correctly
  return ($loc -replace '\\(\.?)([^\\]{3})[^\\]*(?=\\)','\$1$2')
} 

function Get-SystemUptime ($computer = "$env:computername") {
  $lastboot = [System.Management.ManagementDateTimeconverter]::ToDateTime("$((gwmi  Win32_OperatingSystem -computername $computer).LastBootUpTime)")
  $uptime = (Get-Date) - $lastboot
  Write-Host "System Uptime for $computer is: " -NoNewline -ForegroundColor $Color_Value_2
  Write-Host $uptime.days -NoNewline -ForegroundColor $Color_Label
  Write-Host " days " -NoNewline -ForegroundColor $Color_Value_2
  Write-Host $uptime.hours -NoNewline -ForegroundColor $Color_Label
  Write-Host " hours " -NoNewline -ForegroundColor $Color_Value_2
  Write-Host $uptime.minutes -NoNewline -ForegroundColor $Color_Label
  Write-Host " minutes " -NoNewline -ForegroundColor $Color_Value_2
  Write-Host $uptime.seconds -NoNewline -ForegroundColor $Color_Label
  Write-Host " seconds" -ForegroundColor $Color_Value_2
}

# Call "Main" Function
. Main

# SIG # Begin signature block
# MIISBgYJKoZIhvcNAQcCoIIR9zCCEfMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU3C9SbvolyquBkZm/ktAb3cfd
# pMiggg47MIIGcDCCBFigAwIBAgIBJDANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ2WhcNMTcxMDI0MjIw
# MTQ2WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J
# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj
# Id6ZNavcSa6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
# 05dCGUAS2h8Xc+DOBLCe24K3mD3HdBTkpFPe13ojeOkFqJScYLr4998lcCFk/U8j
# /Fl9CorlpWwgoVCCxHW757dv7THLviuK1t2oI6jpfgQzwTurXkGeiziEWYBiPnUM
# KXmD0ADxQehIEOF6m3PANy1sxlt5rG/Mg4YhB7MbfjBGrfsh7Vtgsgdk+oaqRao3
# OCh/9C4/oNBKpw==
# SIG # End signature block


I recently gave a presentation on the Citrix XenApp cmdlets for the Atlanta Citrix User Group.  For the presentation I wanted to show a real world example of the cmdlets in use. I decided to take a script that I wrote in July of 2007 ,which is still in use today, and convert it to use the new XenApp PowerShell cmdlets.  Shown below is the original script.

The purpose of the script is to automatically create a published desktop for our XenApp servers as they are built.  It uses MFCOM to perform the work.  One of the pain points in this script is that I had to actually copy the icon from an existing published desktop. This is a problem that I don’t have with the cmdlets.

#=============================================================================
#= Script Name:      Citrix Admin Desktop Publishing Script
#= Created On:       07/11/2007
#= Author:           Mark E. Schill
#= File:             Publish-Desktop.ps1
#= Usage:
#= Version:          1.0
#= Purpose:          Publishes an Admin Desktop on the server it is run from.
#= Requirements:       Must be run on a Citrix server in the same farm
#= Last Updated:     07/11/2007
#= History:
#=                   07/11/2007 1.0 - Initial Revision
#=
#=                        Copyright (C) 2007 Mark E. Schill
#==============================================================================

function Publish-Desktop( [string]$ServerName)
{
    $CPSReferenceApp = New-Object -comOBject MetaFrameCOM.MetaFrameApplication
    $CPSReferenceApp.Initialize(3, "Applications/Admin/Desktops/WMT13-CTX-DC1 Desktop")
    $CPSReferenceApp.LoadData($true)
    $CPSReferenceIcon = $CPSReferenceApp.WinAppObject.IconObject

    $ServerName = $ServerName.ToUpper()
    $CPSFarm = New-Object -ComObject MetaFrameCOM.MetaFrameFarm
    $CPSFarm.Initialize(1)
    $CPSApp = $CPSFarm.AddApplication(3)
    $CPSApp.AppName = "$ServerName Desktop"
    $CPSApp.Description = "Admin Desktop for Remote Administration"
    $CPSApp.ParentFolderDN = "Applications/Admin/Desktops"
    $CPSApp.PNFolder = "Admin\Desktops"
    $CPSApp.WinAppObject.DefaultInitProg = ""
    $CPSApp.WinAppObject.DefaultWorkDir = ""
    $CPSApp.WinAppObject.DefaultWindowColor = 4 # 32 Bit
    $CPSApp.WinAppObject.DefaultWindowType = 6 # MFWINWindowPercent
    $CPSApp.WinAppObject.DefaultWindowScale = 95 # 95%

    $CPSApp.WinAppObject.PNAttributes = 8
    $CPSApp.WinAppObject.SetIconBitmaps( $CPSReferenceIcon.IconMaskSize, $CPSReferenceIcon.IconMaskBitmap, $CPSReferenceIcon.IconDataSize, $CPSReferenceIcon.IconDataBitmap)
    $CPSApp.AddUser( 1, "CDC", 4, "CTX-Admins")
    $CPSApp.AddUser( 1, "CDC", 4, "CTX-Support")
    $CPSApp.SaveData()
    $CPSAppBinding = New-Object -ComObject MetaFrameCOM.MetaFrameAppSrvBinding
    $CPSAppBinding.Initialize(6,$ServerName,$CPSApp.DistinguishedName)
    if ($CPSAppBinding)
    {
        Write-Host "Publishing"$CPSApp.BrowserName"on $ServerName" -foregroundcolor Green
        $CPSApp.AddServer($CPSAppBinding)
        $CPSApp.SaveData()

    }
    else
    {
        Write-Host "Unable to create App Binding" -foregroundcolor red
    }

}

Publish-Desktop("$env:COMPUTERNAME")

Shown below is the new “script”. As you can see it is actually a one-liner if you take out the function stuff. Also I don’t have the icon issue because it automatically creates the correct icon.

function Publish-Desktop( [string]$ServerName)
{
	New-XAApplication -ApplicationType ServerDesktop -DisplayName "$ServerName Desktop" -FolderPath "Applications/Admin/Desktops" -Description "Admin Desktop for Remote Administration" -ClientFolder "Admin\Desktops" -WindowType "95%" -ColorDepth TrueColor -Accounts "$ServerName\Administrators" -Servernames $Servername
}

As promised here is my PowerPoint presentation and demo code for the presentation I gave at the Atlanta Citrix User Group titled “Managing XenApp with Windows PowerShell”

Presentation: Managing XenApp with Windows PowerShell

Demo Code: Demo.ps1

 Atlanta Citrix User Group – www.acug.org
Tuesday, April 27th

Topics of Discussion

Mark Schill, User Group Member, - Powershell Scripting XenApp

Mark is the WebMaster for the ACUG.org website and Charter Member of the current rendition of the Atlanta Citrix User Group.  Mark has been implementing and supporting Citrix Products in the Atlanta area for years and is a prolific PowerShell scripter.  MFCOM is out and Powershell is in, so come listen to Mark give the User Group a foundation of PowerShell scripting on XenApp.

Marcia Orea, Citrix Systems Senior SE – Whats new with XenApp 6.0 – Overview, Demo, and Q&A

Marcia Orea is a Senior Southeast SE for Citrix Systems and this will be her first presentation at an ACUG meeting.  Come hear Marcia tell the User Group whats new in XenApp 6.0!

The User Group meetings provide members with an opportunity to share and learn about common issues and utilization of Server Based Computing  technology.  Additional segments include troubleshooting tips, best practices, enterprise solutions, technology trends, vendor presentations and upcoming activities of interest. 

When: Tuesday,  April 27, 2010
          11:00am – 1:30 pm
          Lunch will be provided (BBQ) and sponsored by Citrix Systems, inc

Where: Citrix Systems Support Office
           2001 Westside Pkwy
           Suite 260
           Alpharetta, GA 30004

Registration:  Our ACUG Website is down so to register for this event please send an e-mail to events@ACUG.org or simply reply to this message.  Registration enables us get a count of who will be attending so we can get an accurate food and drink order in.

A successful User Group is a partnership between all members

Last night we had the inaugural meeting of the Atlanta PowerShell User Group at the New Horizons Computer Learning Center in Sandy Springs. It was an excellent first meeting and we had really good attendance. I think we even got someone new excited about PowerShell.

 

IMG_0246IMG_0245IMG_0244IMG_0243IMG_0242

 

Entertainment was provided by Jonathan Walz and his son with excellent Yoyo demonstrations.

IMG_0249

A special hats off to Glenn Sizemore (@glnsize) for driving all the way from Augusta (2 hours one way) just to attend the meeting. Now that is dedication.

A tremendous thank you to Janis at New Horizons. Janis and New Horizons were very accommodating and provided us with a great place to hold our meeting. They have a great facility so if you are looking for a training or certification center in Atlanta give them a ring.

Our next meeting will be on Tuesday April 20th 2010 from 6-8 pm at the same location so mark it on your calendar.

Powered by WordPress Web Design by SRS Solutions © 2010 String Theory Design by SRS Solutions