Jump to content
Welcome to our new Citrix community!
  • 6

Powershell Script repository.


Randy White1709153608

Question

I've looked for a script repository on here or a common place that people post scripts they have created and I havent had much luck. So I thought I would start a thread and see where it goes from there. Use the scripts in this thread with caution and ask questions if your not familiar with Powershell.

 

Also I should have mentioned that if you see something wrong with any of these scripts or maybe a better way of doing something please feel free to give suggestions. 

  • Like 4
Link to comment
  • Answers 58
  • Created
  • Last Reply

Top Posters For This Question

Recommended Posts

  • 1
On 5/24/2018 at 7:59 AM, Luke Petterson said:

$a = Get-BrokerDesktopGroup | foreach ($Name in $a.Name) {Get-BrokerAccessPolicyRule -DesktopGroupName $Name | select $Name, -expandproperty IncludedUsers} | Export-CSV C:\Xenapp7_BrokerDesktopGroup.csv

 

This will get you closer to what you want (but someone else may be able to tweak it better for you):

$groups = get-brokeraccesspolicyrule 
$groups | select-object @{n='APRName'; e={$_.Name}},DesktopGroupName -ExpandProperty IncludedUsers | export-csv c:\Xenapp7_BrokerDesktopGroup.csv

 

Each BrokerAccessPolicyRule includes the desktopGroupName it is associated with, so you could just pull back the rules to find all desktop groups. If you only want the rules for specific groups, then the command would need updating. Mostly you were using pipes in places where you needed separate commands

Because both the AccessPolicyRule and the Expanced IncludedUsers contain a name field, I renamed the APR name field in the output, but you could exclude it, but I find it helpful to track the multiple access policy rules per delivery group especially if delivering apps and desktops.  And if you only want the group name returned vs. sid/upn, additional work is needed.

 

I may not have time to play anymore with this until next week, so if someone has a better way to do this, feel free to correct.

 

 

  • Like 1
Link to comment
  • 1
Quote

 

Warning, this is still a work in progress but wanted to get the main part out.

This one is still new and I am still working to get it cleaned up and more efficient. At this time, this gets all of the Applications and Desktop with it's corosponding Access assignments. Please note I was not able to find anything, anywhere about getting the Assignment groups for the Application groups or nested Desktops in a Delivery Group. This script reports on all of those. In our environment, we have more than one Desktop in a Delivery group. Doing just a Get-brokerDekstop to get users only pulled the main desktop info back. Then, we have many Application Groups which had their own assignment groups configured with the applications. Please let me know if you have any thoughts on cleaning this up. I use this info getting spit out with the Gridview so our Support teams can see what user is tied to what resource or what AD group they would need for a certain App or desktop. I am still working on a version like this so it automatically tells what apps a user has including any AD groups they may be associated with.

 

 

# ***************************************************************************************************

# Created on 12/26/2018

# by Dwayne Dunivan

<#

Purpose:

Get all AD groups and Users assigned to all Desktops, Applications and Application Groups

#>

Add-PSSnapin Citrix.Broker.Admin.*

$objAllData = @()

#########################GET Desktops######################

$objAllDesktops = Get-BrokerDesktop -MaxRecordCount 1500 -Property DesktopGroupName | Select -Unique *

$loopCounter = 0

ForEach($Desktop in $objAllDesktops.DesktopGroupName){

$loopCounter++

Write-Progress -Id 1 -Activity "Working On $Desktop" -PercentComplete ([math]::round($loopCounter / $($objAllDesktops.DesktopGroupName).count*100)) -CurrentOperation "$([math]::round($loopCounter / $($objAllDesktops.DesktopGroupName).count*100))% complete" -Status "Please wait."

$objAllUsers = Get-BrokerDesktop -MaxRecordCount 1500 -DesktopGroupName "$Desktop"| select -ExpandProperty AssociatedUserFullNames

$loopCounter2 = 0

If($objAllUsers -eq $null) {

$objData = New-Object System.Object

$objData | Add-Member -Type NoteProperty -Name "Item" -Value $Desktop

$objData | Add-Member -Type NoteProperty -Name "AD/EID" -Value "N/A"

$objAllData += $objData

}

ForEach($User in $objAllUsers) {

$loopCounter2++

Write-Progress -Id 2 -Activity "Working On $User" -PercentComplete ([math]::round($loopCounter2 / $($objAllUsers).count*100)) -CurrentOperation "$([math]::round($loopCounter2 / $($objAllUsers).count*100))% complete" -Status "Please wait."

$objData = New-Object System.Object

$objData | Add-Member -Type NoteProperty -Name "Item" -Value $Desktop

$objData | Add-Member -Type NoteProperty -Name "AD/EID" -Value $User

$objAllData += $objData

}

}

Write-Progress -id 1 -Completed -Status "Complete" -Activity *

Write-Progress -id 2 -Completed -Status "Complete" -Activity *

##############################GET Applications#########################

$objAllApp = Get-BrokerApplication -MaxRecordCount 1500 -Property ApplicationName

$loopCounter = 0

ForEach($App in $objAllApp.ApplicationName){

$objData = New-Object System.Object

#$objData | Add-Member -Type NoteProperty -Name "Application" -Value $App

$loopCounter++

Write-Progress -Id 1 -Activity "Working On $app" -PercentComplete ([math]::round($loopCounter / $($objAllApp.ApplicationName).count*100)) -CurrentOperation "$([math]::round($loopCounter / $($objAllApp.ApplicationName).count*100)) % complete" -Status "Please wait."

$objAllUsers = Get-BrokerApplication -MaxRecordCount 1500 -PublishedName "$App"| select -ExpandProperty AssociatedUserFullNames

$loopCounter2 = 0

If($objAllUsers -eq $null) {

$objData = New-Object System.Object

$objData | Add-Member -Type NoteProperty -Name "Item" -Value $App

$objData | Add-Member -Type NoteProperty -Name "AD/EID" -Value "N/A"

$objAllData += $objData

}

Foreach($User in $objAllUsers) {

$loopCounter2++

Write-Progress -Id 2 -Activity "Working On $User" -PercentComplete ([math]::round($loopCounter2 / $($objAllUsers).count*100)) -CurrentOperation "$([math]::round($loopCounter2 / $($objAllUsers).count*100)) % complete" -Status "Please wait."

$objData = New-Object System.Object

$objData | Add-Member -Type NoteProperty -Name "Item" -Value $App

$objData | Add-Member -Type NoteProperty -Name "AD/EID" -Value $User

$objAllData += $objData

}

}

Write-Progress -id 1 -Completed -Status "Complete" -Activity *

Write-Progress -id 2 -Completed -Status "Complete" -Activity *

####################################Get Desktop Groups#######################

$objAllDesktopItems = Get-BrokerEntitlementPolicyRule -MaxRecordCount 1500 | Select PublishedName, IncludedUsers

$loopCounter = 0

ForEach($DesktopItem in $objAllDesktopItems){

$objData = New-Object System.Object

$loopCounter++

Write-Progress -Id 1 -Activity "Working On $($DesktopItem.PublishedName)" -PercentComplete ([math]::round($loopCounter / $($objAllDesktopItems).count*100)) -CurrentOperation "$([math]::round($loopCounter / $($objAllDesktopItems).count*100)) % complete" -Status "Please wait"

$loopCounter2 = 0

Foreach($User in $DesktopItem.IncludedUsers.Fullname) {

$loopCounter2++

Write-Progress -Id 2 -Activity "Working On $($User)" -PercentComplete ([math]::round($loopCounter2 / $($DesktopItem.IncludedUsers.Fullname).count*100)) -CurrentOperation "$([math]::round($loopCounter2 / $($DesktopItem.IncludedUsers.Fullname).count*100)) % complete" -Status "Please wait"

$objData = New-Object System.Object

$objData | Add-Member -Type NoteProperty -Name "Item" -Value $DesktopItem.PublishedName

$objData | Add-Member -Type NoteProperty -Name "AD/EID" -Value $User

$objAllData += $objData

}

}

Write-Progress -id 1 -Completed -Status "Complete" -Activity *

Write-Progress -id 2 -Completed -Status "Complete" -Activity *

###################GET Application groups######################################

$strAllApplications = Get-BrokerApplication | Select ApplicationName, AssociatedApplicationGroupUUIDs

$loopCounter = 0

$objAppGroupUsers = @()

Foreach($strApp in $strAllApplications){

$loopCounter++

Write-Progress -Id 1 -Activity "Working On $($strApp.ApplicationName)" -PercentComplete ([math]::round($loopCounter / $($strAllApplications).count*100)) -CurrentOperation "$([math]::round($loopCounter / $($strAllApplications).count*100)) % complete" -Status "Please wait"

If(($strApp.AssociatedApplicationGroupUUIDs.GUID) -ne $null) {

$objData0 = New-Object System.Object

$objData0 | Add-Member -Type NoteProperty -Name "AppName" -Value $($strApp.ApplicationName)

$objData0 | Add-Member -Type NoteProperty -Name "GroupName" -Value $((Get-BrokerApplicationGroup -UUID "$($strApp.AssociatedApplicationGroupUUIDs)") | Select Name).name

$objData0 | Add-Member -Type NoteProperty -Name "Users" -Value $((Get-BrokerApplicationGroup -UUID "$($strApp.AssociatedApplicationGroupUUIDs)") | Select AssociatedUserFullNames).AssociatedUserFullNames

$objAppGroupUsers += $objData0

}

}

$objAppUser = @()

Foreach($strAppGroup in $objAppGroupUsers){

$arrUsers = $strAppGroup.users

$loopCounter2 = 0

Foreach($strUser in $arrUsers) {

$objData = New-Object System.Object

$loopCounter2++

Write-Progress -Id 2 -Activity "Working On $($strUser)" -PercentComplete ([math]::round($loopCounter2 / $($arrUsers).count*100)) -CurrentOperation "$([math]::round($loopCounter2 / $($arrUsers).count*100)) % complete" -Status "Please wait"

$objData | Add-Member -Type NoteProperty -Name "Item" -Value $($strAppGroup.AppName)

$objData | Add-Member -Type NoteProperty -Name "AD/EID" -Value $strUser

$objAlldata += $objData

}

}

 

Write-Progress -id 1 -Completed -Status "Complete" -Activity *

Write-Progress -id 2 -Completed -Status "Complete" -Activity *

$completeDesktopList = $objDesktopList | Select Item, AD/EID

$completeDesktopList | Export-Csv "D:\Reports\Desktop_App_User_List.csv" -NoTypeInformation -force

  • Like 1
Link to comment
  • 0

Function to reset users session

 

Loads Powershell snapins

Script is for killing sessions from PS prompt. I'm in the process creating a tool that calls this function. 

 

msiexec /i "unc_path\Powershell_Snapins\Broker_PowerShellSnapIn_x64.msi" /quiet
asnp citrix*
$ddc = "controller"
 
function reset-user{
[cmdletbinding()]
param (
        [Parameter(Mandatory=$true)]
        [string]$User
    )
        Invoke-command -Computer $ddc -scriptblock {param([string]$LocalUser) ; Add-PSSnapin Citrix* ; Get-BrokerSession -max 10000 | Where-Object brokeringusername -eq  "$env:USERDOMAIN\$($LocalUser)"| Stop-BrokerSession } -ArgumentList $user
}
 

Example

reset-user username

  • Like 1
Link to comment
  • 0

Reset Citrix receiver and clear temp logs 

 

Function reset-receiver{
[cmdletbinding()]
   $a = new-object -comobject wscript.shell 
          $intAnswer = $a.popup(   
   "This will reset Citrix Receiver`
You will get prompt to reboot `
your computer, are you Sure?", 0,"",4) 
    If ($intAnswer -eq 6) 
        { 
            start-process "C:\Program Files (x86)\Citrix\ICA Client\SelfServicePlugin\CleanUp.exe" "-cleanUser"
        }
        sleep 20 
        
        Get-Process | sort description | ?{ $_.description -like "Citrix*" } | Stop-Process -Force
        Remove-Item $env:LOCALAPPDATA\temp\CTXReceiverLogs -Recurse -force -ErrorAction SilentlyContinue
        Remove-Item $env:LOCALAPPDATA\temp\*.ica -ErrorAction SilentlyContinue
        Remove-Item $env:LOCALAPPDATA\temp\CTXReceiverLogs\1\* -Recurse -force -ErrorAction SilentlyContinue
        Remove-Item $env:LOCALAPPDATA\temp\CTXReceiverLogs\2\* -Recurse -force -ErrorAction SilentlyContinue
        Remove-Item $env:LOCALAPPDATA\temp\CTXReceiverLogs\3\* -Recurse -force -ErrorAction SilentlyContinue
        Remove-Item $env:LOCALAPPDATA\temp\CTXReceiverLogs -Recurse -force -ErrorAction SilentlyContinue
   $a = new-object -comobject wscript.shell 
   $intAnswer = $a.popup("Are you ready to restart your computer?", 0,"Issue fixed",4) 
    If ($intAnswer -eq 6) 
        { 
            shutdown -r -t 000
        } 
        
 
 
}

 

  • Like 1
Link to comment
  • 0

Clears Write Cache. I have this set to a logoff action to clean up the write cache if I no longer store event logs there or if I'm done troubleshooting a problem. 

 

$writecache= (Get-WMIObject Win32_Volume | ? { $_.Label -eq 'WCDisk'-or $_.Label -eq "WRcache" } |select name).name
$driveletter = test-path $writecache
if($driveletter -eq $true)
{
Remove-Item -path $writecache\'$RECYCLE.BIN' -Recurse -force
}
  • Like 1
Link to comment
  • 0

The get-eventlog works but it didnt do everything I wanted so I made a few changes 

 

Function get-logs{
[cmdletbinding()]
param (
        
        [Parameter(Mandatory=$true,Helpmessage="Enter a logname, Application, System, Security,Setup  ")]
        [string]$logname,
        [Parameter(Mandatory=$true,Helpmessage="Enter a Event level, error, warning, critical, informational")]
        [string]$eventlevel,
        [Parameter(Mandatory=$true,Helpmessage="Enter a Computer name or computernames seperated by ,")]
        [string]$computers,
        [Parameter(Mandatory=$true, Helpmessage="Enter the path you want to file saved to")]
        [string]$filename
 
 
    )
foreach ($computer in $computers)
{
if (Test-Connection $computer.Trim() -Count 1 -Quiet) 
{
Get-EventLog -Newest 20000 -LogName $logname -EntryType $eventlevel -ComputerName $computer.Trim() | Export-CSV $filename -NoClobber -NoTypeInformation -Append
}
 
}
}
  • Like 1
Link to comment
  • 0

This function gets the powered on of powered off machine for a delivery group 

 

 

Function Get-machinesPowerStatus{
[cmdletbinding()]
 
param (
        
        [Parameter(Mandatory=$true,Helpmessage="Enter a Delivery Group")]
        [string]$deliverygroup,
        [Parameter(Mandatory=$true,Helpmessage="Enter a Power State on/off")]
        [string]$PowerState
    )
       
         Get-BrokerMachine -AdminAddress ddc -DesktopGroupName $deliverygroup | Where-Object {$_.PowerState -eq $PowerState} | select hostedmachinename,Powerstate
}
  • Like 1
Link to comment
  • 0

Hi,

 

Latest I wrote,

 

Users that have been idle longer than 60min get disconnected.

Uers that have been disconnected longer than 60min get logged off.

 

 

----

 

$sessions = quser | select -skip 1 | %{
$item = "" | Select "Username", "SessionName", "ID", "State", "Idle", "Logon"
$item.Username = $_.Substring(1,20).Trim()
$item.SessionName = $_.Substring(22,10).Trim()
$item.ID = $_.Substring(40,5).Trim()
$item.State = $_.Substring(46,6).Trim()
$item.Idle = $_.Substring(59,4).Trim()
$item.Logon = $_.Substring(65,16).Trim()
$item
}
 
 
foreach ($session in $sessions){
if ($session.idle -match "\:" -And $session.idle -ne "."){ $idle = [timespan]$session.idle 
if ($idle.TotalMinutes -gt 60){tsdiscon.exe  $session.Id}
}}
 
foreach ($session in $sessions){
if ($session.idle -match "\:" -And $session.idle -ne "."){ $idle = [timespan]$session.idle 
if ($idle.TotalMinutes -gt 60 -And $session.state -match "Dis*" ){logoff.exe $session.id}
}}
  • Like 2
Link to comment
  • 0

Sometimes I just need to find out if the network is having a problem, I start with a little script that just pings and records to a file that I can look for dropped packets. 

 

$destination = Read-Host "Specify destination host name or IP address "
$logonly="Y"
$filelocation="c:\"+$env:computername+"_ping_results.txt"
Do{
    If($logonly -notmatch '^[yn]$' ) { Write-Warning "Invalid Entry" }
    $logonly = Read-Host "Log to a file and Output to console? (Y/N) "
} While($logonly -notmatch '^[yn]$')
 
Write-Host "Default ping vaules: -count 999999 -delay 2" -BackgroundColor Yellow -ForegroundColor Red
 
if ($logonly -eq "y") { 
    write-host "Pinging host:"$destination". Log file location: "$filelocation -BackgroundColor Yellow -ForegroundColor Red
    test-connection $destination -count 999999 -delay 2 -Verbose | format-table @{n='TimeStamp';e={Get-Date}},@{Expression={$_.Address};Label='Destination'},IPV4aDDRESS,ResponseTime  | tee-object -filepath $filelocation -Append 
}
 
else { 
    test-connection $destination -count 999999 -delay 2 -Verbose | format-table @{n='TimeStamp';e={Get-Date}},@{Expression={$_.Address};Label="Destination"},IPV4aDDRESS,ResponseTime 
}

 

  • Like 1
Link to comment
  • 0
Restarts computers that are powered on but unregistered. 

 

 

asnp citrix*

$bdg = Get-BrokerMachine -AdminAddress "Your_ddc" -MaxRecordCount 100000 | where {$_.PowerState -ne "Off" -and $_.InMaintenanceMode -eq $false -and $_.RegistrationState -eq "UNRegistered"}  | select MachineName,RegistrationState,InMaintenanceMode,Powerstate

foreach ($Machine in $bdg) 

{

        #Restart-Computer $Machine

        New-BrokerHostingPowerAction -Action 'Reset' -MachineName $Machine.MachineName

}

$filedate = (get-date).Month.ToString() + (Get-Date).Day.tostring() + (get-date).Year.tostring()

$outputfile = "c:\XD_rebooted_" + $filedate + ".csv"

$bdg | Out-File $outputfile 
  • Like 1
Link to comment
  • 0
Get most of what I find important 

 

 

function Get-OSInfo {

    [CmdletBinding()]

    param (

        #[Parameter(ValueFromPipeline=$True,

        #           ValueFromPipelineByPropertyName=$True)]

        [string[]]$computername,

 

        [string]$errorlog = 'c:\errors.txt',

                

        [switch]$logerrors

    )

        

 

    PROCESS {

        foreach ($computer in $computername) {

            Try {

                $os = Get-WmiObject -EA Stop –Class Win32_OperatingSystem –ComputerName $computer 

                $cs = Get-WmiObject -EA Stop –Class Win32_ComputerSystem –ComputerName $computer 

                $bios = Get-WmiObject -EA Stop –Class Win32_BIOS –ComputerName $computer

                $cpu = Get-WmiObject -EA Stop -class Win32_processor -ComputerName $computer 

                $props = @{'ComputerName'=$computer;

                           'OSVersion'=$os.version;

                           'SPVersion'=$os.servicepackmajorversion;

                           'OSBuild'=$os.buildnumber;

                           'OSArchitecture'=$os.osarchitecture;

                           'Manufacturer'=$cs.manufacturer;

                           'Model'=$cs.model;

                           'BIOSSerial'=$bios.serialnumber

                           'CPU Count'=$CPU.Count

                           'Memory'= [Math]::round(($cs.TotalPhysicalMemory/1gb),2) 

                           'CPU Speed'= $CPU.MaxClockSpeed[0]}

                           

                $obj = New-Object -TypeName PSOBject -Property $props

                $obj.PSObject.TypeNames.Insert(0,'Get-OS.OSInfo')

                #Write-Output $obj

                $obj | Export-Csv c:\test4.csv -Append

 

            } Catch {

                if ($logerrors) {

                    $computer | Out-File $errorlog -append

                }

                Write-Warning "$computer failed"

            }

                            

        }

            

 

    }

}
Link to comment
  • 0
Today i needed to get all the groups from the OU and count each member. 

 

This will give you the group name and how many members are in the group. 

 

Import-Module ActiveDirectory

$groups = Get-ADGroup -Filter {GroupCategory -eq 'security'} -SearchBase 'Path to OU' -Properties *

    foreach ($group in $groups) 

    {

    $groups | select name, {$_.members.count} | export-csv c:\Group_count.csv -Append -NoClobber -NoTypeInformation
Link to comment
  • 0

I needed to find out what machines in a deliverygroup were in maintenance mode and list them out.  

 

 

$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object Hostedmachinename).hostedmachinename
 
foreach($machine in $machines){
 
    Get-BrokerMachine -HostedMachineName $machine | format-list hostedmachinename,InMaintenanceMode
    }
 

 

Link to comment
  • 0

I wanted to know what machines were in maintenance mode in a certain delivery group. 

 

 

$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object Hostedmachinename).hostedmachinename
 
foreach($machine in $machines){
 
    $machinelist = Get-BrokerMachine -HostedMachineName $machine
        if($machinelist.InMaintenanceMode -eq $true){
            write-host "$machine is in maintenance mode"
            }else  {
            write-host "$machine is not in maintenance mode"
            }
 
    }
Link to comment
  • 0

This will search an OU then pull out machines that are older than 60 days, test the connection to those to confirm if they are valid or not then output them to a list. I found almost 600 machines I was able to delete. 

 

Import-Module ActiveDirectory

$enddate = Get-Date 
$machines=(Get-ADComputer -filter * -SearchBase 'OU=this,OU=is,OU=my,DC=domain,DC=com' -Properties * | Select Name, lastlogondate |Where-Object {$_.LastLogonDate -lt ($enddate).AddMonths(-2)} |Sort  lastlogondate).name
foreach ($machine in $machines) 
 {
      if (test-Connection -ComputerName $machine -count 1 -ErrorAction SilentlyContinue) 
             {
                Write-Output "$machine is valid" | Out-File c:\machine_valid.csv -Append -NoClobber
             }
                Write-Output "$machine is not valid" | Out-File c:\machine_not_valid.csv -Append -NoClobber 
 }
Link to comment
  • 0
Function GetInfo {
 
      [CmdletBinding()]
 
      Param(
      [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] 
      [string[]]$computername, 
      [string]$logfile = 'c:\scripts\unreachable.txt',
      [string]$outfile = 'c:\scripts\computerinfo.csv'
 
      )
 
BEGIN {
 
      Remove-Item $logfile –erroraction silentlycontinue
 
}
 
PROCESS {
 
      Foreach ($computer in $computername) {
 
            $continue = $true
            try {
 
                  $os = Get-WmiObject –class Win32_OperatingSystem –computername $computer –erroraction Stop
 
            } catch {
 
                  $continue = $false
                  "$computer is not reachable" | Out-File $logfile -append
 
            }
 
 
            if ($continue) {
 
                  $bios = Get-WmiObject –class Win32_BIOS –computername $computer
                  $os = Gwmi win32_operatingsystem -cn $computer
                  $mem = get-wmiobject Win32_ComputerSystem -cn $computer | select @{name="PhysicalMemory";Expression={"{0:N2}" -f($_.TotalPhysicalMemory/1gb).tostring("N0")}},NumberOfProcessors,Name,Model
                  $cpuinfo = "numberOfCores","NumberOfLogicalProcessors","maxclockspeed","addressWidth"
 
 
                  [string[]]$cpudata = Get-WmiObject -class win32_processor –computername $computer -Property $cpuinfo | Select-Object -Property $cpuinfo
 
                  $phyv = Get-WmiObject win32_bIOS -computer $computer | select serialnumber
 
                  $res = "Physical” # Assume "physical machine" unless resource has "vmware" in the value or a "dash" in the serial #                 
 
 
                  if ($phyv -like "*-*" -or $phyv -like "*VM*" -or $phyv -like "*vm*") { $res = "Virtual" } # else
 
                  #{                  
 
                   # Find all active NICs and IP of the NIC
 
                   $Networks = gwmi Win32_NetworkAdapterConfiguration -ComputerName $computer | ? {$_.IPEnabled}
 
                     foreach ($Network in $Networks) {[string[]]$IPAddress += ("[" + $Network.IpAddress[0] + " " + $Network.MACAddress + "]")}
 
                   $ActiveIPs = $IPAddress
 
                   $Networks = gwmi -ComputerName $computer win32_networkadapter | where-object { $_.physicaladapter }
 
                     foreach ($Network in $Networks) {
 
                       #if ({$_.$Network.MACAddress}) {[string[]]$MACinfo += "#" + $Network.DeviceID + "-" + $Network.MACAddress} else {[string[]]$MACinfo += "#" + $Network.DeviceID + "-Dis"}
 
                       [string[]]$MACinfo += "#" + $Network.DeviceID + "-" + $Network.MACAddress
 
                     }
 
                   $obj = New-Object –typename PSObject
 
# DISPLAY Section ($obj - output to screen)
# - For "report-ONLY," you can comment out the "$obj" (11 lines) below
 
                   $obj | Add-Member –membertype NoteProperty –name ComputerName –value ($computer) –PassThru |
                          Add-Member –membertype NoteProperty –name Hardware –value ($res) -PassThru |
                          Add-Member –membertype NoteProperty –name OperatingSystem –value ($os.Caption) -PassThru |
                          Add-Member –membertype NoteProperty –name ServicePack –value ($os.ServicePackMajorVersion) -PassThru |
                          Add-Member –membertype NoteProperty –name "PhysicalMemory" –value ($mem.PhysicalMemory) -PassThru |
                          Add-Member –membertype NoteProperty –name Processors –value ($mem.numberofprocessors)  -PassThru |
                          Add-Member –membertype NoteProperty –name CPUInfo –value ($cpudata) -PassThru |
                          Add-Member –membertype NoteProperty –name IPAddress –value ($ActiveIPs) -PassThru  |
                          Add-Member –membertype NoteProperty –name NICs –value ($MACinfo) -PassThru |
                          Add-Member –membertype NoteProperty –name Serial -value ($phyv)
 
# REPORT Section ($csv - output to file)
 
                   $csv = $computer + "," `
                           + $res + "," `
                           + $os.Caption +"," `
                           + $os.ServicePackMajorVersion + "," `
                           + $mem.PHysicalmemory + "," `
                           + $mem.numberofprocessors + "," `
                           + $cpudata + "," `
                           + $ActiveIPs + "," `
                           + $MACinfo + "," `
                           + $phyv
 
                   Write-Output $obj
                   #Write-Output $csv - uncomment this to debug the report output line
                   Write $csv | Out-File $outfile -append
 
                 # } # End of Else ($res = "Physical)
 
            } # End of IF (continue)
            
      } # End of ForEach
 
  } # End of Process
 
END {}
 
} # End Function
 
 
 
write-host "Installing the Citrix Controller Pieces"
Import-Module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\getinfo.psm1
msiexec /i "c:\Broker_PowerShellSnapIn_x64.msi" /quiet
sleep 20
asnp citrix*
sleep 10
#$deliverygroup = Read-Host "Please enter Delivery Group"
$deliverygroup = Get-Content "c:\all_delivery_groups.txt"
 
#$servers = get-content C:\p6-15.csv
foreach ($d in $deliverygroup)
{
    $filename = "c:\Server_details\$d.csv"
$servers = Get-BrokerMachine -AdminAddress DDC -MaxRecordCount 10000 | Where-Object { $_.DesktopGroupName -eq $d } | Select-Object hostedMachineName
foreach ($server in $servers.HostedMachineName)
{
If (Test-Connection $server -count 1 -Quiet)
{
 
GetInfo -computername $server | select ComputerName, Hardware, OperatingSystem, PhysicalMemory, Processors | Export-csv $filename -NoClobber -NoTypeInformation -Append
}
}
}
 

 

Link to comment
  • 0

This is awesome, thanks Randy.

 

Here's a script I use to identify logged on users who have installed Receiver as themselves instead of our package which includes the command line parameters that we want.

 

 

add-pssnapin -name citrix.xenapp.* -ErrorAction SilentlyContinue
 
get-xasession -full |
Where-Object {$_.ClientDirectory -like "C:\Users*"} |
Format-table -AutoSize -ShowError ClientName, AccountName, ClientDirectory, ClientBuildNumber, ClientAddress | Out-String -Width 256 | Out-File -Append .\Clients.txt
Link to comment
  • 0
Lists VDIs that have not been used for two months. 
Exports list to a CSV file under script path then adds tag,
puts VDI in maintenance mode and shuts it down.
Needs to be run on XenDesktop 7x controller.

 

<######################################################################################  
        Lists VDIs that have not been used for two months. 
        Exports list to a CSV file under script path then adds tag, 
        puts VDI in maintenance mode and shuts it down.
        Needs to be run on XenDesktop 7x controller.
 
       
Author: Sebastian Trumstedt 
#######################################################################################>
 
 
#Change DOMAIN to your Active directory domain name for example CONTOSO.
$Domain = "DOMAIN"
 
Write-Host -ForegroundColor Green "Searching for VMs not connected to for 2 months." 
Write-Host -ForegroundColor Green "Found VMs will be put in maintenance mode and shutdown." 
Write-Host -ForegroundColor Green "Script tested on XenDesktop 7x controller." 
 
#Load Citrix PS snappins
Add-PSSnapin Citrix*
 
$Lastused =((Get-Date).AddMonths(-2).ToString('yyyy-MM-dd HH:mm:s'))
$machines = Get-BrokerMachine -MachineName "$Domain\*" | 
Where-Object {$_.LastConnectionTime -lt $Lastused -and $_.LastConnectionTime -gt "1999-12-30 00:00:00" -and $_.InMaintenanceMode -match "False" -and $_.SessionCount -lt "1" } 
#Exit script if null
IF([string]::IsNullOrWhiteSpace($machines)) {            
    Write-Host -ForegroundColor Red "No machines in scope, exiting script."
    Exit            
Write-Output $machines | select DNSName,LastConnectionTime
#Export list to CSV file.
$machines | select DNSName,LastConnectionTime,{$_.AssociatedUserNames} | Export-CSV "$PSScriptRoot\$(get-date -f yyyy-MM-dd) Unused VDIs.csv"
 
#Add a tag to the VM
$machines_tags = Get-BrokerDesktop -MachineName "$Domain\*" | 
Where-Object {$_.LastConnectionTime -lt $Lastused -and $_.LastConnectionTime -gt "1999-12-30 00:00:00" -and $_.InMaintenanceMode -match "False"} 
$tag = "VM put in maintenance mode by script $(get-date -f yyyy-MM-dd-hh-mm)"
New-Brokertag -name $tag 
Foreach ($machines_tag in $machines_tags){ 
    Add-BrokerTag -name $tag -Desktop $machines_tag
}
 
#Put VM in maintenance mode.
Set-BrokerMachineMaintenanceMode -InputObject $machines $true
 
#Shut down VM.
Foreach ($machine in $machines){ 
New-BrokerHostingPowerAction -MachineName $machine.MachineName -Action Shutdown
}
 
Write-Host -ForegroundColor Green "Script finished."

 

Link to comment
  • 0

I'm looking for a report-script to provide to Human Resources in order to provide them any user activity performed externally; they're asking if a user logged on from outside the office (!= Internal IP) and how long their session was active. If the associated applications could be provided that to would be useful.

 

Lastly HR only cares about external sessions after hours, so anytime after 5:00pm till 8:00am the following morning. Can this be obtained?

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...