Get Logon Server From List Of Computers

Brass Contributor

Hello I am trying to find the logon server $env:logonserver from a list of computers in a .txt file and have the results exported out to a .csv file for a domain migration project I am working on.  I attempted this whit the code below but it is not exporting anything useful. Can someone tell me what I am doing wrong and what the proper code would be to get this info? 
Thanks in advance!!

$computers = get-content .\computers.txt
$results = foreach ($computer in $computers){
invoke-command -computer $computer -scriptblock {$env:logonserver}}
$results | export-csv .\logonservers.csv
3 Replies


You dont need to use the variable before the foreach.

Use this.

$computers = get-content C:\MyFile.txt
 foreach ($computer in $computers){
$results=invoke-command -computer $computer -scriptblock {$env:logonserver}
Add-Content C:\MyResult.txt -Value $results 
Thanks for the reply Farismalaeb. I mad the changes you suggested and it returned no results. The .txt file is empty. My goal is to have it output a .csv file with two columns.

Computername Logonserver

For each of the computers in the computers.txt file.



Taking a quick look, the LogonServer environment variable only seems to be set for Interactive (logonType = 2, or 10 in the case of RDP for the RemoteTerminal logonType.)


Running remote commands will use the Network logon (logonType = 3), and not all logon processes are executed in this scenario. This impacts the session environment variables created, with some like LogonServer not being created.


If you run the following command, you'll find that LogonServer isn't listed.



Invoke-Command -ComputerName -ScriptBlock {
    $ev = [System.Environment]::GetEnvironmentVariables();
    $ev.Keys |
        ForEach-Object {
            [PSCustomObject] @{
                Variable = $_;
                Value = $ev[$_];
    } |
        Sort-Object -Property Variable |
            Format-Table -AutoSize PSComputerName, Variable, Value;