Posts RSS Comments RSS 117 Posts and 170 Comments till now

Archive for September, 2007

Citrix, Citrix, and more Citrix!

It has been a while since I dove into the MFCom pool. Most of the Citrix functions I wrote where at the very beggining of my Powershell Adventure. I decided to go through and rewrite some of them and post the others.

So… here you go.

I broke these down into three sections
- Citrix Farm Functions
- Citrix App Functions
- Citrix Server Functions

If you get a chance to use these let me know if you run into any troubles… I did test them thoroughly.. but you never know.

Other than Publish/Unpublish/Remove they shouldn’t change anything.

UPDATED: I added information about functions before each section. And a list at the bottom!

Farm functions
————–
# Returns Farm Object.
# -Server: Any PS should do.. I recommend ZDC though) !!REQ!!
Get-CitrixFarm

# Returns a collection of Server Objects
# -zone= This will be the zone name (normally the subnet i.e. 10.1.1.0) !!REQ!!
Get-CitrixOnline

# Returns Load Evaluators Information
# -Server: Any PS should do.. I recommend ZDC though) !!REQ!!
Get-CitrixLE

# Returns Printer Drivers install in Farm
# -Server: Any PS should do.. I recommend ZDC though) !!REQ!!
# This can take a REAL long time
Get-CitrixPrintDrivers

# Returns Polices in the Farm
# -Server !!REQ!! (any PS should do.. I recommend ZDC though)
Get-CitrixPolicies

  1. #########################################
  2. ####     Citrix Farm Functions       ####
  3. #########################################
  4. # Get Citrix Farm
  5. function Get-CitrixFarm{
  6.     param($Server)
  7.     $type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$Server)
  8.     $mfarm = [system.Activator]::CreateInstance($type)
  9.     $mfarm.Initialize(1)
  10.     return $mFarm
  11. }
  12.  
  13. # Get Online Servers by Zone
  14. function Get-CitrixOnline {
  15.     Param($zone)
  16.     $mfzone = New-Object -ComObject MetaFrameCOM.MetaFrameZone
  17.     $mfzone.Initialize($zone)
  18.     $servers = $mfzone.OnlineServers
  19.     $servers
  20. }
  21.  
  22. # Get Citrix Load Evaluators (only 4.0/4.5)
  23. function Get-CitrixLE{
  24.     Param($server=$(throw "Server is Required"))
  25.     function Load-Farm{
  26.         param($srv)
  27.         $type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
  28.         $mfarm = [system.Activator]::CreateInstance($type)
  29.         $mfarm.Initialize(1)
  30.         return $mFarm
  31.     }
  32.     $Farm = load-farm $server
  33.     if($Farm.LoadEvaluators){
  34.         foreach($eval in $Farm.LoadEvaluators)
  35.         {
  36.             $eval.loadData(1)
  37.             "+ Load Evaluator: {0}" -f $eval.LEName
  38.             $servers = $eval.AttachedServers(1)
  39.             if($servers.count -ne 0)
  40.             {
  41.                 "  + Servers"
  42.                 $servers | %{"    - {0}" -f $_.ServerName}
  43.             }
  44.             $rules = $eval.rules | Select-Object RuleType,HWM,LWM,Schedules
  45.             if($rules.count -ne 0)
  46.             {
  47.                 "  + Rules"
  48.                 foreach($rule in $rules)
  49.                 {
  50.                     "    - {0}" -f $rule
  51.                 }
  52.             }
  53.         }
  54.     }
  55. }
  56.  
  57. # Gets the Citrix Printer Drivers for the Farm (Can be REAL slow)
  58. function Get-CitrixPrintDrivers{
  59.     Param($server=$(throw "Server is Required"))
  60.     function Load-Farm{
  61.         param($srv)
  62.         $type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
  63.         $mfarm = [system.Activator]::CreateInstance($type)
  64.         $mfarm.Initialize(1)
  65.         return $mFarm
  66.     }
  67.     $farm = Load-Farm $Server
  68.     $farm.Drivers
  69. }
  70.  
  71. # Gets Citrix Policies
  72. function Get-CitrixPolicies{
  73.     param($Server)
  74.     function Load-Farm{
  75.         param($srv)
  76.         $type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
  77.         $mfarm = [system.Activator]::CreateInstance($type)
  78.         $mfarm.Initialize(1)
  79.         return $mFarm
  80.     }
  81.     $farm = Load-Farm $server
  82.     $type = [System.Type]::GetTypeFromProgID("MetaFrameCOM.MetaFrameUserPolicy")
  83.     foreach($pol in $Farm.policies($type))
  84.     {
  85.         $pol.loadData(1)
  86.         "+ Name: {0}" -f $pol.Name
  87.         "  - Description: {0}" -f $pol.Description
  88.         "  - Enabled: {0}" -f $pol.Enabled
  89.         if($pol.AllowedAccounts)
  90.         {
  91.             "  + AllowedAccounts"
  92.             foreach($aa in $pol.AllowedAccounts)
  93.             {
  94.                 "    - {0}" -f $aa.AccountName
  95.             }
  96.         }
  97.         if($pol.UserPolicy2)
  98.         {
  99.             "  + UserPolicy"
  100.             $props = $pol.UserPolicy2 | Get-Member -membertype Property | %{$_.Name} | Sort-Object Name
  101.             foreach($prop in $props)
  102.             {
  103.                 if(($pol.UserPolicy2.$prop -match "\d") -and ($pol.UserPolicy2.$prop -ne 0))
  104.                 {
  105.                     "     - {0}:{1}" -f $prop,$pol.UserPolicy2.$prop
  106.                 }
  107.             }
  108.         }
  109.         write-Output " "
  110.     }
  111. }

App functions
————–
# Returns User Count for an App or All Apps
# -FarmServer !!REQ!! (any PS should do.. I recommend ZDC though)
# -app: Name of Application
# This loops CTRL+C to break
Get-ApplicationUserCount

# Returns Server(s) user is logged into via Citrix
# -LoginName: Login Name of user (Domain\User) !!REQ!!
# -Verbose: Details about User
Find-CitrixUser

# Returns Servers published for Application or just Count
# -app: Name of Application !!REQ!!
# -count: Switch… if set just returns count of servers
Get-CitrixServers

# Returns Users currently using APP
# -app: !!REQ!!
# -count: Switch… if set just returns count of servers
Get-CitrixAppUsers

  1. #########################################
  2. ####     Citrix App Functions        ####
  3. #########################################
  4. # Outputs the number of Users using a Citrix App or Apps
  5. function Get-ApplicationUserCount {
  6.     Param([string]$app,[string]$farmServer = $(throw ‘$FarmServer is Required’))
  7.     function List-AllCitrixApps{
  8.         Param($mFarm)
  9.         ForEach($app in $mFarm.Applications)
  10.         {
  11.             $name = $app.BrowserName.PadRight(25)
  12.             $count = "$($app.Sessions.Count)"
  13.             $count = $count.PadRight(10)
  14.             Write-Host "$name $count"
  15.         }
  16.     }
  17.     function List-App{
  18.         param($mApp,$mfFarm)
  19.         ForEach($app in $mfFarm.Applications)
  20.         {
  21.             if($app.BrowserName -eq "$mApp")
  22.             {
  23.                 $name = $app.BrowserName.PadRight(25)
  24.                 $count = "$(($app.Sessions | ?{$_.SessionState -eq 1}).Count)"
  25.                 $count = $count.PadRight(10)
  26.                 Write-Host "$name $count"
  27.             }
  28.         }
  29.     }
  30.     function Load-Farm{
  31.         $type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
  32.         $mfarm = [system.Activator]::CreateInstance($type)
  33.         $mfarm.Initialize(1)
  34.         return $mFarm
  35.     }
  36.     Write-Host
  37.     $title1 = "Application".PadRight(25)
  38.     $title2 = "===========".PadRight(25)
  39.     Write-Host "$title1 User Count" -ForegroundColor White
  40.     Write-Host "$title2 ==========" -ForegroundColor Red
  41.     $mf = Load-Farm $farmServer
  42.     While($true)
  43.     {
  44.         $oldpos = $host.UI.RawUI.CursorPosition
  45.         If($app)
  46.         {
  47.             List-App $app $mf
  48.         }
  49.         else
  50.         {
  51.             List-AllCitrixApps $mf
  52.         }
  53.         sleep(5)
  54.         $host.UI.RawUI.CursorPosition = $oldpos
  55.     }
  56.     Write-Host ""
  57. }
  58.  
  59. # Finds what Server a User is on
  60. function Find-CitrixUser {
  61.     Param([string]$LoginName,[switch]$verbose)
  62.     $user = $LoginName.Split("\")[1]
  63.     $Domain = $LoginName.Split("\")[0]
  64.     $mfuser = New-Object -ComObject MetaframeCOM.MetaframeUser
  65.     $mfuser.Initialize(1,$Domain,1,$user)
  66.     Write-Host
  67.     Write-Host "User: $($mfuser.UserName) found on the Following:"
  68.     foreach ($s in $mfuser.Sessions)
  69.     {
  70.         if($verbose)
  71.         {
  72.             Write-Host
  73.             Write-Host "$($s.ServerName)"
  74.             Write-Host "-=-=-=-=-=-"
  75.             Write-Host "AppName          : $($s.AppName)" -foregroundcolor yellow
  76.             Write-Host "SessionName      : $($s.SessionName)" -foregroundcolor yellow
  77.             Write-Host "SessionID        : $($s.SessionID)" -foregroundcolor yellow
  78.             Write-Host "ClientAddress    : $($s.ClientAddress)" -foregroundcolor yellow
  79.             Write-Host "ClientEncryption : $($s.ClientEncryption)" -foregroundcolor yellow
  80.             Write-Host
  81.             Write-Host "Processes"
  82.             Write-Host "========="
  83.             foreach ($proc in $s.Processes)
  84.             {
  85.                 Write-Host $proc.ProcessName -foregroundcolor Green
  86.             }
  87.             Write-host
  88.         }
  89.         else
  90.         {
  91.             write-Host "   -> $($s.ServerName)"
  92.         }
  93.     }
  94. }
  95.  
  96. # Gets Servers Published for specified App (or just returns count)
  97. function Get-CitrixServers {
  98.     Param($app = $(throw ‘$app is required’),[switch]$count)
  99.     $mfm = New-Object -com MetaFrameCOM.MetaFrameFarm
  100.     $mfm.Initialize(1)
  101.     $servers = $mfm.Applications | ?{$_.AppName -eq $app}
  102.     $servers = $servers.Servers | sort -Property ServerName
  103.     if($count)
  104.     {
  105.         Write-Host
  106.         Write-Host "Found [$($Servers.Count)] Servers for Application [$app]" -ForegroundColor White
  107.         Write-Host
  108.     }
  109.     else
  110.     {
  111.         Write-Host ""
  112.         Write-Host "Found [$($Servers.Count)] Servers for Application [$app]" -ForegroundColor White
  113.         Write-Host "———————————————–" -ForegroundColor gray
  114.         foreach($server in $servers){Write-Host "$($server.ServerName)" -ForegroundColor Green}
  115.         Write-Host "———————————————–" -ForegroundColor gray
  116.         Write-Host "Found [$($Servers.Count)] Servers for Application [$app]" -ForegroundColor White
  117.         Write-Host ""
  118.     }
  119. }
  120.  
  121. # Returns Users currently using Citrix App
  122. function Get-CitrixAppUsers {
  123.     Param($app = $(throw ‘$app is required’),[switch]$count)
  124.     $ErrorActionPreference = "SilentlyContinue"
  125.     Write-host
  126.     $mfm = New-Object -com MetaFrameCOM.MetaFrameFarm
  127.     $mfm.Initialize(1)
  128.     $users = $mfm.Applications | ?{$_.AppName -eq $app}
  129.     $Users = $users.Sessions | sort -Property UserName
  130.     if($count){
  131.         Write-Host "Found [$($Users.Count)] Users for Application [$app]" -ForegroundColor White
  132.         Write-Host
  133.     }
  134.     else{
  135.         Write-Host ""
  136.         Write-Host "Found [$($Users.Count)] Users for Application [$app]" -ForegroundColor White
  137.         Write-Host "—————————————————–" -ForegroundColor gray
  138.         foreach($user in $Users){
  139.             If($User.SessionState -eq 1){
  140.                 Write-Host ($User.UserName).PadRight(10) -ForegroundColor Green -NoNewline
  141.             }
  142.             else{
  143.                 Write-Host ($User.UserName).PadRight(10) -ForegroundColor yellow -NoNewline
  144.             }
  145.         }
  146.         Write-Host
  147.         Write-Host "—————————————————–" -ForegroundColor gray
  148.         Write-Host "Found [$($Users.Count)] Users for Application [$app]" -ForegroundColor White
  149.         Write-Host
  150.     }
  151. }

Server functions
————–
# Returns A Server Object
# -Server: Name of the Server !!REQ!!
Get-CitrixServer

# Publishes Application to Server(s)
# -app: !!REQ!!
# -Server: Name of Server
# PIPED: It will take Servers via Pipe. It expects a list or Citrix Server Object
Publish-CitrixApplication

# UnPublishes ALL Application from Server(s)
# -Server: Name of Server
# PIPED: It will take Servers via Pipe. It expects a list or Citrix Server Object
UnPublish-CitrixServer

# Remove Specific Application from Server(s)
# -app: !!REQ!!
# -Server: Name of Server
# PIPED: It will take Servers via Pipe. It expects a list or Citrix Server Object
Remove-CitrixApplication

# Gets Published Applications from Server(s)
# -Server: Name of Server
# PIPED: It will take Servers via Pipe. It expects a list or Citrix Server Object
Get-CitrixApplications

# Returns Count of Logged on Users from Server(s)
# -Server: Name of Server
# PIPED: It will take Servers via Pipe. It expects a list or Citrix Server Object
Get-TSUserCount

  1. ##########################################
  2. ####     Citrix Server Functions      ####
  3. ##########################################
  4. # Get a Citrix Server Object
  5. function Get-CitrixServer{
  6.     Param($Server)
  7.     $type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeServer",$Server)
  8.     $mfServer = [system.Activator]::CreateInstance($type)
  9.     $mfServer.Initialize(6,$Server)
  10.     $mfServer
  11. }
  12.  
  13. # Publish Application to Server(s)
  14. function Publish-CitrixApplication{
  15.     Param([string]$server,[string]$app)
  16.     Begin{
  17.         Write-Host
  18.         function cPublish {
  19.             Param([string]$Srv,[string]$myapp)
  20.             $Srv = $Srv.toUpper()
  21.             $mfSrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
  22.             $mfSrv.Initialize(6,"$Srv")
  23.             $mfApp = New-Object -ComObject MetaFrameCOM.MetaFrameApplication
  24.             $mfApp.Initialize(3,"Applications\$myapp")
  25.             $mfApp.LoadData($true)
  26.             $mfAppBinding = New-Object -ComObject MetaFrameCOM.MetaFrameAppSrvBinding
  27.             $mfAppBinding.Initialize(6,$Srv,"Applications\$app")
  28.             if($mfAppBinding)
  29.             {
  30.                 Write-Host "Publishing App[$myapp] on Server [$Srv]" -ForegroundColor Green
  31.                 $mfApp.AddServer($mfAppBinding)
  32.                 $mfApp.SaveData()
  33.             }
  34.             else
  35.             {
  36.                 Write-Host "Unable To Create App Binding" -ForegroundColor Red
  37.             }
  38.         }
  39.         $process = @()
  40.     }
  41.     Process{
  42.         if($_){
  43.             if($_.ServerName){
  44.                 $process += $_.ServerName
  45.             }
  46.             else{
  47.                 $process += $_
  48.             }
  49.         }
  50.     }
  51.     End{
  52.         if($Server){$Process += $Server}
  53.         foreach($s in $process){
  54.             cPublish -srv $s -myapp $app
  55.             Write-Host
  56.         }
  57.     }
  58. }
  59.  
  60. # UnPublish All Application from Server(s)
  61. function UnPublish-CitrixServer{
  62.     Param([string]$server)
  63.     Begin{
  64.         function cUnPublish {
  65.             Param([string]$Srv)
  66.             $Srv = $Srv.toUpper()
  67.             $mfSrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
  68.             $mfSrv.Initialize(6,"$Srv")
  69.             If($mfSrv.Applications.Count -gt 0)
  70.             {
  71.                 Write-Host "Removing All Published Applications from $Srv" -ForegroundColor Red
  72.                 Write-Host "===================================================" -ForegroundColor Green
  73.                 ForEach($a in $mfSrv.Applications)
  74.                 {
  75.                     $myApp = $a.AppName
  76.                     $a.LoadData(1)
  77.                     Write-Host "Removing App [$myApp] from Server [$Srv]" -ForegroundColor White
  78.                     $a.RemoveServer($Srv)
  79.                     $a.SaveData()
  80.                 }
  81.             }
  82.             else
  83.             {
  84.                 Write-Host "No Published Applications for $Srv" -ForegroundColor Red
  85.             }
  86.         }
  87.         Write-Host
  88.         $process = @()
  89.     }
  90.     Process{
  91.         if($_){
  92.             if($_.ServerName)
  93.             {
  94.                 $process += $_.ServerName
  95.             }
  96.             else
  97.             {
  98.                 $process += $_
  99.             }
  100.         }
  101.     }
  102.     End{
  103.         if($Server){$Process += $Server}
  104.         foreach($s in $process){
  105.             cUnPublish $s
  106.             Write-Host
  107.         }
  108.     }
  109. }
  110.  
  111. # Remove a Citrix App from Server
  112. function Remove-CitrixApplication {
  113.     Param([string]$server,[string]$app)
  114.     Begin{
  115.         function RemoveApp {
  116.             Param([string]$Srv,[string]$myapp)
  117.             $AppRemoved = $false
  118.             $Srv = $Srv.toUpper()
  119.             $mfSrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
  120.             $mfSrv.Initialize(6,"$Srv")
  121.             If($mfSrv.Applications.Count -gt 0)
  122.             {
  123.                 ForEach($a in $mfSrv.Applications)
  124.                 {
  125.                     If($a.AppName -eq "$myapp")
  126.                     {
  127.                         Write-Host "Removing App [$myApp] from Server [$Srv]" -ForegroundColor Green
  128.                         $a.RemoveServer($Srv)
  129.                         $a.SaveData()
  130.                         $AppRemoved = $true
  131.                     }
  132.                 }
  133.             }
  134.             else
  135.             {
  136.                 Write-Host "No Applications Published for $Srv" -ForegroundColor Red
  137.                 $AppRemoved = $true
  138.             }
  139.             If($AppRemoved -eq $false)
  140.             {
  141.                 Write-Host "This Application not Published for $Srv" -ForegroundColor Red
  142.             }
  143.         }
  144.         Write-Host
  145.         $process = @()
  146.     }
  147.     Process{
  148.         if($_)
  149.         {
  150.             if($_.ServerName){
  151.  
  152.                 $process += $_.ServerName
  153.             }
  154.             else
  155.             {
  156.                 $process += $_
  157.             }
  158.         }
  159.     }
  160.     End{
  161.         if($Server){$Process += $Server}
  162.         if($process.Length -eq 0){$Process += get-content env:COMPUTERNAME}
  163.         foreach($s in $process)
  164.         {
  165.             RemoveApp -Srv $s -myapp $app
  166.             Write-Host
  167.         }
  168.     }
  169. }
  170.  
  171. # List Citrix Apps Published to Server
  172. function Get-CitrixApplications {
  173.     Param([string]$Server)
  174.     Begin {
  175.         Write-Host
  176.         function cGetApps {
  177.             param([string]$srv)
  178.             $srv = $srv.ToUpper()
  179.             $mfsrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
  180.             $mfsrv.Initialize(6,"$srv")
  181.             Write-Host "SERVER $srv" -foregroundcolor Red
  182.             Write-Host "==================" -ForegroundColor Green
  183.             If($mfSrv.Applications.Count -gt 0) {
  184.                 $mfSrv.Applications | %{Write-Host "Published:   $($_.AppName.ToUpper())"}
  185.             }
  186.             else {
  187.                 Write-Host "No Applications Published for $srv" -foregroundcolor white
  188.             }
  189.         }
  190.         $process = @()
  191.     }
  192.     Process{
  193.         if($_){
  194.             if($_.ServerName){
  195.                 $process += $_.ServerName
  196.             }
  197.             else{
  198.                 $process += $_
  199.             }
  200.         }
  201.     }
  202.     End {
  203.         if($Server){$Process += $Server}
  204.         foreach($s in $process){
  205.             cGetApps $s
  206.             Write-Host
  207.         }
  208.     }
  209. }
  210.  
  211. # Return Current Terminal Server User Count
  212. function Get-TSUserCount {
  213.     Param([string]$Server)
  214.     Begin{
  215.         function TsUserCount {
  216.             param([string]$srv)
  217.             $msg = "Checking For Users on Server [$srv]"
  218.             $msg = $msg.PadRight($pad)
  219.             Write-host $msg -ForegroundColor White
  220.             $msg = "==========================================="
  221.             $msg = $msg.PadRight($pad)
  222.             Write-host $msg -ForegroundColor gray
  223.             $msg = "Terminal Server User Count on Server "
  224.             $msg1 = "[$srv]"
  225.             $msg1 = $msg1.PadRight($pad)
  226.             $ts = Get-WmiObject Win32_PerfFormattedData_TermService_TerminalServices -ComputerName $srv
  227.             $count = $ts.activeSessions
  228.             If($count -eq 0)
  229.             {
  230.                 Write-host "$msg [Users:$count]" -ForegroundColor Green
  231.             }
  232.             else
  233.             {
  234.                 Write-host "$msg [Users:$count]" -ForegroundColor Yellow
  235.             }
  236.         }
  237.         $process = @()
  238.     }
  239.     Process{
  240.         if($_){
  241.             if($_.ServerName)
  242.             {
  243.                 $process += $_.ServerName
  244.             }
  245.             else
  246.             {
  247.                 $process += $_
  248.             }
  249.         }
  250.     }
  251.     End{
  252.         if($Server){$Process += $Server}
  253.         if($process.Length -eq 0){$Process += get-content env:COMPUTERNAME}
  254.         foreach($s in $process)
  255.         {
  256.             TSUserCount $s
  257.             Write-Host
  258.         }
  259.     }
  260. }

Farm functions
————–
Get-CitrixFarm
Get-CitrixOnline
Get-CitrixLE
Get-CitrixPrintDrivers
Get-CitrixPolicies

App functions
————–
Get-ApplicationUserCount
Find-CitrixUser
Get-CitrixServers
Get-CitrixAppUsers

Server functions
————–
Get-CitrixServer
Publish-CitrixApplication
UnPublish-CitrixServer
Remove-CitrixApplication
Get-CitrixApplications
Get-TSUserCount

Test-Port (kinda like portqry without verbose output)

We had a little dicussion on www.powershelllive.com forums about the most efficient way to Test a machine before trying a WMI query against it (as it has a log timeout.) My first suggestion was to use a ping (WMI style) but Jeff from http://blog.sapien.com brought up a valid point… what if ICMP is NOT Allowed…

Enter Test-Port. This nifty little script uses the TCPClient Class to test connectivity. Stay tuned as I am planning some mods.

Test-Port
- Takes parameter $srv for Server Name
- Takes Parameter for Port, Defaults to 135 for RPC mapper.
- Takes Timeout.. defaults to 3000 (miliseconds)
- If it cannot connect within timeout… Returns $false
- If it gets exception connecting to port… Returns $false
- If it connects… Returns $True

  1. function Test-Port{
  2.     Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)
  3.     $ErrorActionPreference = "SilentlyContinue"
  4.     $tcpclient = new-Object system.Net.Sockets.TcpClient
  5.     $iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
  6.     $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
  7.     if(!$wait)
  8.     {
  9.         $tcpclient.Close()
  10.         if($verbose){Write-Host "Connection Timeout"}
  11.         Return $false
  12.     }
  13.     else
  14.     {
  15.         $error.Clear()
  16.         $tcpclient.EndConnect($iar) | out-Null
  17.         if($error[0]){if($verbose){write-host $error[0]};$failed = $true}
  18.         $tcpclient.Close()
  19.     }
  20.     if($failed){return $false}else{return $true}
  21. }

Run-Command.ps1 : Run External Commands with Power!

I was working late tonight and we had to run a bunch of third party EXEs and such. We do this a good bit so I can’t always avoid calling external executables and I also find psexec.exe much easier than any powershell way to run remote commands. That said I find myself constantly writing this.

  1. $servers = Get-Content $file
  2. foreach($server in $servers)
  3. {
  4.    Do Something Here Like
  5.    psexec \\$server mycmd.exe param1
  6. }

I decided to write a script call Run-Command.ps1.
This will take three parameters
- File (list of servers to process)
- Cmd (Command to run with %S% where you want the server name to be replaced)
- Check (just shows what command would run)
- Will also take Piped Input

Example:
PS> .\Run-Command.ps1 -file c:\serverlist.txt -cmd “psexec \\%S% mycmd.exe Hello World” -check

Run-Command.ps1

  1. Param($file,$cmd,[switch]$whatif,[switch]$verbose)
  2. Begin{
  3.     function Ping-Server {
  4.         Param([string]$srv)
  5.         $pingresult = Get-WmiObject win32_pingstatus -f "address=’$srv’"
  6.         if($pingresult.statuscode -eq 0) {$true} else {$false}
  7.     }
  8.     $servers = @()
  9. }
  10. Process{
  11.     if($_<