Un Known
Un Known

Reputation: 169

Startup PowerShell script, Export-Csv not exporting LogonServer variable

I have a PC which is continuously logging in, running a script, then logging off and rebooting to repeat the process.

$StartTime = Get-Date
...
(other code here, including delay)
...
$LServer = $env:logonserver
$ShutTime = Get-Date

New-Object -TypeName PSCustomObject -Property @{
    StartTime = $StartTime
    ShutTime = $ShutTime
    LogonServer = $LServer 
} | Export-Csv -Path "C:\Apps\DCResults.csv" -Append

When I execute the script manually, the file is updated with the correct information i.e. 3 columns of data are filled. But when the script executes on Windows startup, the LogonServer isn't wrriten to the CSV file. That column remains blanks, whereas the other two columns are correct.

EDIT: And actually, it doesn't have to be a .CSV, just a file I can put in Excel to do analysis on. If there's a better way to write to a file...

Upvotes: 0

Views: 719

Answers (4)

Bill_Stewart
Bill_Stewart

Reputation: 24585

The LOGONSERVER environment variable, if set, refers to the computer that logged on the current user (i.e., the user account running your script). For a local account, LOGONSERVER (again, if set) will be the local computer.

Upvotes: 0

brendan62269
brendan62269

Reputation: 1106

I would configure an autologon user: http://support.microsoft.com/kb/324737

Make sure your logon user is a domain user and also a member of the local admins group. Then set the script to run either on startup from the startup folder or in: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Configure the job in the registry to launch via cmd/bat file (just like the scheduled task). The script will run and produce output for any user who logs on who has rights to the folder and file even if you break your autologon user. I would also add a few second delay using the shutdown command so that the reboot part can be easily broken with shutdown -a

Upvotes: 0

Burt_Harris
Burt_Harris

Reputation: 6884

The LogonServer environment variable isn't defined until a user logs in. If you are running script in the machine startup script, the is no user logged in. Perhaps if you ran the script as a Login script it would do at you want.

Upvotes: 0

JKStinn
JKStinn

Reputation: 25

Would something like this work instead:

$LServer = (gwmi Win32_NtDomain | select DomainControllerName | where DomainControllerName -ne $null ).DomainControllerName[0] -replace '\\'

Upvotes: 1

Related Questions