Need help with my script

I have the below script which i am using to retrive information for a specific desktop .
Now i wanted to retrive details for all the destkop that i have it in a text file. Problem
is i could only get the one record of the desktop , not all records . Could some one help me what i am doing wrong here. Thanks.

$Desktops = get-content c:\temp\desktoplist.txt

foreach ($Desktop in $Desktops) {
switch -wildcard ($Desktop) {
    "UK*"{$servers = @("", "")}
    "US*"{$servers = @("")}
    "SG*"{$servers = @("")}

$DesktopDetail = foreach ($server in $servers) {
    Get-BrokerDesktop -machinename domain\$Desktop -Adminaddress $server
    New-Object -Typename PSObject -property @{ DodName = $desktopdetail.DNSName
                                                                                 State = $destkopdetail.SessionState

if ($DesktopDetail) {
else {
    "No machine with name {0} found on server(s): {1}" -f $Desktop, ($Servers -join ",")

You assign $DesktopDetail variable outside of your cycle (and btw use it inside cycle!)
properly worked version of code can be like this

$haveresult = $false # error cheking if no result found at any server
foreach ([...]) {
  $desktopdetail = Get-BrokerDesktop [...]
  if ($desktopdetail) {
    $haveresult = $true
    New-Object [...] #use $desktopdetail here and output result to screen/pipeline
if (-not $haveresult)
  write-error '[...]'

Hi Suresh,

You did not assign the object returned by Get-BrokerDesktop to a variable to access the properties DNSName and SessionState for your custom PSObject, and a closing curly bracket was missing to close the first foreach loop.

Try below:


An alternative would be to pipe Get-BrokerDesktop to Select-Object and select only the properties you are interested in.


Thanks Daniel /Max

I will give it a try and let you know :)…

Hi Daniel
I have tried your method. But it is only showing the one desktop record. The text contains 10 desktop . Basically i am trying to export the result to CSV file. When i excecute this script it displays the result for all 10 but it does not store the result in the $desktopdetail . :frowning:

That is correct. You will need an array variable outside of “foreach ($Desktop in $Desktops)” to collect the value of $DesktopDetail for each iteration of the loop.


Thanks Daniel Works perfectly . Cheers.
Max i have tried your method as well it works too . Thank you for spending your valuble time to help me :slight_smile: Cheers :):slight_smile: