Link to home
Start Free TrialLog in
Avatar of Axter
AxterFlag for United States of America

asked on

Run Powershell script on startup before user log on

I have a PowerShell script which I used to add machine to a domain.  The purpose is to allow me to snap a VM to a clean state, before machine has been added to a domain.

I would like to be able to setup the snapshot of the VM so that when it starts up, it automatically runs the PowerShell script.
I tried populating the following registry key, but this only works after user logs on.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

I then tried the following registry key, but nothing seems to happen:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunServicesOnce

I also tried creating a scheduled task to call the script, and configured the task to run on start up, but nothing happen.

I think with the last two approach, the script is getting called too early, before a required service is loaded.

I know the script works, because it works when I call it on command line, and it works when I use the log on method (RunOnce) registry key.
Here's the PowerShell script:
$domainName="mydomain"
$domainPw="mypassword"
$domainAcc=$domainName + "\MyAdminUserName"

$comp = get-wmiobject Win32_ComputerSystem
$comp.JoinDomainOrWorkGroup($domainName,$domainPw,$domainAcc,$null,3)

$reboot = (gwmi -Class Win32_OperatingSystem)
$reboot.psbase.scope.options.enableprivileges = $true
$reboot.reboot()

Open in new window


Here's the DOS script which is used to call the PowerShell script:
rem schtasks /Delete /TN AddMachineToTestlabDomain
rem Above is only needed when using task schedule method
powershell Set-ExecutionPolicy RemoteSigned
powershell c:\AddMachineToTestlabDomain.ps1

Open in new window



Does anyone know how I can configure Windows 2008 machine to automatically get added to a domain on bootup without requiring user to log on?
Or how to call above script on bootup without requiring user to log on?
ASKER CERTIFIED SOLUTION
Avatar of larry urban
larry urban
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Axter

ASKER

Not all the VM's have the same local administrative password, so I wouldn't be able to create a single script to configure the VM's.

I currently have a script to copy the PowerShell and batch file to the VM.
The script also adds the registry key settings.

Then I take a snapshot of the VM.
If I have to use method with local password, it wouldn't work on all of the VM's.

If I don't get a better posted method, I'll still this approach.