Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Startup Program on W2012 R2

Posted on 2014-09-18
14
Medium Priority
?
9,380 Views
Last Modified: 2014-09-23
How do I add a windows program to the startup list in W2012R2?

Also, is there a way to make a windows program run as a service?  I found an article on this, but the resource kit it referred to is not installed on my server.  If I could make the program a service that would be ideal.
0
Comment
Question by:No1Coder
  • 8
  • 6
14 Comments
 
LVL 12

Expert Comment

by:David Paris Vicente
ID: 40330152
Hi No1Coder,

You can tweak this PowerShell Script to install or remove a service.

Install.ps1

$serviceName = "WorkManagerDemoService" 
$serviceDisplayName = "WorkManager Demo Service" 
$serviceDescription = "WorkManager Demo Service" 
$serviceExecutable = "WindowsService1.exe"

# verify if the service already exists, and if yes remove it first 
if (Get-Service $serviceName -ErrorAction SilentlyContinue) 
{ 
    "service already installed, stopping…" 
    # using WMI to remove Windows service because PowerShell does not have CmdLet for this 
    $serviceToRemove = Get-WmiObject -Class Win32_Service -Filter "name=’$serviceName’" 
    $serviceToRemove | Stop-Service 
    $serviceToRemove.delete() 
    "service removed" 
} 
else 
{ 
    # just do nothing 
    "service does not exist" 
}

"installing service…"

# detect current execution directory 
$directoryPath = Split-Path $MyInvocation.MyCommand.Path

# creating credentials which can be used to run my windows service 
#$secpasswd = ConvertTo-SecureString "MyPa$$word" -AsPlainText -Force 
#$mycreds = New-Object System.Management.Automation.PSCredential (".\MyUserName", $secpasswd) 
# OR 
#$myCredentials = Get-Credential

$binaryPath = $directoryPath + "\" + $serviceExecutable

# creating widnows service using all provided parameters, -displayName $serviceName, -credential $myCredentials 
New-Service -name $serviceName -displayName $serviceDisplayName -binaryPathName $binaryPath -startupType Automatic -Description $serviceDescription

Start-Service -Name $serviceName

Get-Service $serviceName

"installation completed"

Pause

Open in new window



Uninstall.ps1
$serviceName = "WorkManagerDemoService"

# verify if the service already exists, and if yes remove it 
if (Get-Service $serviceName -ErrorAction SilentlyContinue) 
{ 
    "service already installed, stopping…" 
    # using WMI to remove Windows service because PowerShell does not have CmdLet for this 
    $serviceToRemove = Get-WmiObject -Class Win32_Service -Filter "name=’$serviceName’" 
    $serviceToRemove | Stop-Service 
    $serviceToRemove.delete() 
    "service removed" 
} 
else 
{ 
    # just do nothing 
    "service does not exist" 
}

Pause

Open in new window


Hope it helps.
0
 

Author Comment

by:No1Coder
ID: 40332422
I hard coded the directory, changed the exe name, etc.  When I execute I get the error below.

New-Service : Service 'WebPingService (WebPingService)' cannot be created due to the following error: Access is denied
At line:1 char:1
+ New-Service -name $serviceName -displayName $serviceDisplayName -binaryPathName  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (WebPingService:String) [New-Service], ServiceCommandException
    + FullyQualifiedErrorId : CouldNotNewService,Microsoft.PowerShell.Commands.NewServiceCommand

The program is at the target location and is not running.

I have never used powershell.  I copied the command to clipboard, opened powershell, and pasted in.
0
 
LVL 12

Expert Comment

by:David Paris Vicente
ID: 40332618
Open powershell as Administrator, then in powershell use this command:
set-executionpolicy -executionpolicy unresctricted

Then try to run again the script, you will need admin rights in that machine.

Let us know.
0
Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

 

Author Comment

by:No1Coder
ID: 40332895
That seemed to help.  I now see the service in the UI.  Says "starting".

The program in question is a windows forms program.  Will the UI appear once the service starts?
0
 

Author Comment

by:No1Coder
ID: 40335183
I am still not able to make this work.  The service gets created, but it will not start.  I tried to remove it with the script provided, but it won't remove.

PS D:\utilities\pingnet> d:\utilities\pingnet\uninstallservice.ps1
service already installed, stopping…
Get-WmiObject : Invalid query "select * from Win32_Service where name=’WebPingService’"
At D:\utilities\pingnet\uninstallservice.ps1:8 char:24
+     $serviceToRemove = Get-WmiObject -Class Win32_Service -Filter "name=’$servic ...
+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

You cannot call a method on a null-valued expression.
At D:\utilities\pingnet\uninstallservice.ps1:10 char:5
+     $serviceToRemove.delete()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

service removed


----------------
the script is running as administrator.  The name matches what I see under services.
0
 
LVL 12

Expert Comment

by:David Paris Vicente
ID: 40336299
First lets address the program to start for every user.

You can add a Reg key for start programs on start up.
Go to your registry and:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

In here create a String value and in the value data, write the path to the program you want to run o start up.

Now the powershell try this way:
$serviceName = "MYserviceName" 

# verify if the service already exists, and if yes remove it 
if (Get-Service $serviceName -ErrorAction SilentlyContinue) 
{ 
    "service already installed, stopping…" 
    # using WMI to remove Windows service because PowerShell does not have CmdLet for this 
    $serviceToRemove = Get-WmiObject -Class Win32_Service|Where-Object -Property Name -eq $serviceName
    $serviceToRemove | Stop-Service 
    $serviceToRemove.delete() 
    "service removed" 
} 
else 
{ 
    # just do nothing 
    "service does not exist" 
}

Pause

Open in new window




On the install Script line 25 "$directoryPath = Split-Path $MyInvocation.MyCommand.Path" change the variable to the physical path were is the program, something like this:
$directoryPath = c:\ProgramFiles\cmd.exe

Let me know if helped.
0
 

Author Comment

by:No1Coder
ID: 40336364
Thank you,  Making progress.

Using the registry key works, however the startup directory for my program must be set.  Is there another registry key for this?

The revised script works better.  The uninstall script works.

I modified the install script, and it created the service, but hangs when it tries to start the service.  I looked in task manager, and the task was there, but it was not visible on the screen.  When I killed the task, the script completed with errors:
PS C:\Windows\system32> Start-Service -Name $serviceName
Start-Service : Service 'WebPingService (WebPingService)' cannot be started due to the following error: Cannot start
service WebPingService on computer '.'.
At line:1 char:1
+ Start-Service -Name $serviceName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
   ServiceCommandException
    + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand




This is a windows forms application.  Is that ok to run as service?
I also tried to start the service from the services admin function. This gives me an error message "Error 1053:  The service did not start or control request in a timely way."
0
 
LVL 12

Expert Comment

by:David Paris Vicente
ID: 40336427
But that Form is called by an executable program?
If not you can´t run as a service.
If not you can create a batch file and run the batch as a service to call the Form.
0
 

Author Comment

by:No1Coder
ID: 40336439
Didn't understand first comment.

This is a windows forms application.  (exe). When I run the executable, it shows a window on my desktop.

Is there a way to set setup directory in registry when doing startup.  If so, my problem is solved.
0
 
LVL 12

Accepted Solution

by:
David Paris Vicente earned 1500 total points
ID: 40336466
The Startup Folder is in:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Try it and let me know.
0
 

Author Comment

by:No1Coder
ID: 40338690
I don't have this directory on my computer.

I need to specify a different folder for the program to run in.

This program was not installed using an install tool, it is just an exe that I copied to the desktop.

I tried calling a batch command file from the registry, but it doesn't work for some reason.

Just trying to get the program to run when the server re-boots.  If I specify the exe in the registry, it runs, but in the wrong directory.
0
 
LVL 12

Expert Comment

by:David Paris Vicente
ID: 40338722
Did you enable the option to show all files and folders?

Open Explorer, press ALT ->TOOLS->Folder Options-> Select the View tab.
Then in Files and Folders->Hidden files and folders-> Select show hidden files, folders, and files.
0
 

Author Comment

by:No1Coder
ID: 40338828
Okay.  I got it to work.

I had to put a shortcut in the folder mentioned above.  The program now starts after reboot, and in the correct directory.

Thanks for your assistance.
0
 

Author Closing Comment

by:No1Coder
ID: 40338830
Never could get service to work, but was able to solve my problem.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Welcome to my series of short tips on migrations. Whilst based on Microsoft migrations the same principles can be applied to any type of migration. My first tip Migration Tip #1 – Source Server Health can be found here: http://www.experts-exchang…
Have you considered what group policies are backwards and forwards compatible? Windows Active Directory servers and clients use group policy templates to deploy sets of policies within your domain. But, there is a catch to deploying policies. The…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

886 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question