views:

3218

answers:

3

Does anyone have a Powershell script to change the credentials used by a Windows service?

+1  A: 

Considering that whithin this class:

$class=[WMICLASS]'\\.\root\Microsoft\SqlServer\ComputerManagement:SqlService'

there's a method named setserviceaccount(), may be this script will do what you want:

# Copyright Buck Woody, 2007
# All scripts provided AS-IS. No functionality is guaranteed in any way.
# Change Service Account name and password using PowerShell and WMI
$class = Get-WmiObject -computername "SQLVM03-QF59YPW" -namespace
root\Microsoft\SqlServer\ComputerManagement -class SqlService

#This remmed out part shows the services - I'll just go after number 6 (SQL
#Server Agent in my case):
# foreach ($classname in $class) {write-host $classname.DisplayName}
# $class[6].DisplayName
stop-service -displayName $class[6].DisplayName

# Note: I recommend you make these parameters, so that you don't store
# passwords. At your own risk here!
$class[6].SetServiceAccount("account", "password")
start-service -displayName $class[6].DisplayName
VonC
+4  A: 

Bit easier - use WMI.

$service = gwmi win32_service -computer [computername] -filter "name='whatever'" $service.change($null,$null,$null,$null,$null,$null,$null,"P@ssw0rd")

Change the service name appropriately in the filter; set the remote computer name appropriately.

Don Jones
A: 

Hi,

I created a text file "changeserviceaccount.ps1" containing the following script:

$account="domain\user"
$password="passsword"
$service="name='servicename'"

$svc=gwmi win32_service -filter $service
$svc.StopService()
$svc.change($null,$null,$null,$null,$null,$null,$account,$password,$null,$null,$null)
$svc.StartService()

I used this as part of by post-build command line during the development of a windows service:

Visual Studio: Project properties\Build Events

Pre-build event command line:

"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe /u

Post-build event command line:

"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe
powershell -command - < c:\psscripts\changeserviceaccount.ps1
AndyM