Change-ServiceAccount


posted by Brian Hagerty
11-13-2009

Downloads: 624
File size: 12.4kB
Views: 3,161

Embed
Change-ServiceAccount
  1. # ============================================================================================== 
  2. # NAME:            Change-ServiceAcct 
  3. # AUTHOR:        Brian Hagerty 
  4. # DATE:            03/04/2009 
  5. # COMMENT:         Changes service account properties for the specified computer(s) 
  6. # MODIFIED:         
  7. # ============================================================================================== 
  8.  
  9. function Change-ServiceAcct ([string]$ServiceName, $DisplayName = $null, $PathName = $null, $ServiceType = $null, $ErrorControl = $null, $StartMode = $null, $DesktopInteract = $true, [string]$StartName, [string]$StartPassword, $LoadOrderGroup = $Null, $LoadOrderGroupDependencies = $Null, $ServiceDependencies = $Null, [switch]$GrantNTRights) { 
  10.     BEGIN {         
  11.         # Display help content, if -? is specified at command line 
  12.         if ($args -contains '-?') { 
  13.             ChangeServiceAccountHelp 
  14.             break 
  15.         
  16.         if($ServiceName -eq $([regex]"[A-z0-9]")) {Throw "A service name must be specified"
  17.     
  18.     PROCESS { 
  19.         Test-Pipeline                    # Ensures valid pipeline input is specified 
  20.         $computer = $_                    # Store incoming computer name from pipeline for readability 
  21.          
  22.         $service = Get-WmiObject -ComputerName $computer -Class WIN32_Service | Where-Object {$_.Name -match $ServiceName
  23.         $OriginalServiceState = $($service.State
  24.          
  25.         if($service -eq $Null) {Throw "The service $ServiceName, does not exist on $computer"
  26.         else
  27.             if($service.State -eq "Started") {  
  28.                 Write-Host -ForegroundColor Green "`n`nComputer: $computer" 
  29.                 Write-Host -ForegroundColor Yellow "Service $($service.Name) is started, stopping the service..." 
  30.                 $service.StopService() 
  31.                  
  32.                 Write-Host -ForegroundColor Cyan "`nApplying changes to the service $($service.Name)..." 
  33.                 $returnCode = $($service.Change($DisplayName,$PathName,$ServiceType,$ErrorControl,$StartMode,$DesktopInteract,$StartName,$StartPassword,$LoadOrderGroup,$LoadOrderGroupDependencies,$ServiceDependencies)).ReturnValue 
  34.                  
  35.                 if($GrantNTRights.IsPresent) { GrantNTRights $StartName $computer
  36.                  
  37.                 ReturnCodeTest $returnCode $OriginalServiceState 
  38.             } else
  39.                 Write-Host -ForegroundColor Green "`n`nComputer: $computer" 
  40.                 Write-Host -ForegroundColor Yellow "Service $($service.Name) is stopped, continuing..." 
  41.                  
  42.                 Write-Host -ForegroundColor Cyan "Applying changes to the service $($service.Name)..." 
  43.                 $returnCode = $($service.Change($DisplayName,$PathName,$ServiceType,$ErrorControl,$StartMode,$DesktopInteract,$StartName,$StartPassword,$LoadOrderGroup,$LoadOrderGroupDependencies,$ServiceDependencies)).ReturnValue 
  44.                  
  45.                 if($GrantNTRights.IsPresent) { GrantNTRights $StartName $computer
  46.                  
  47.                 ReturnCodeTest $returnCode $OriginalServiceState 
  48.             
  49.         
  50.     
  51.  
  52. function GrantNTRights ([string]$user, [string]$computer) { 
  53.     $NTRights = 'C:\Program` Files\Windows` Resource Kits\Tools\ntrights.exe' 
  54.     $NTRightsCmd = $NTRights + " -u $user -m \\$computer +r SeServiceLogonRight" 
  55.     Invoke-Expression $NTRightsCmd 
  56.  
  57. function ReturnCodeTest ([int]$returnCode, [string]$OriginalServiceState) { 
  58.     if ($returnCode -eq 0) { 
  59.         if($OriginalServiceState -eq "Started") { 
  60.             Write-Host -ForegroundColor Cyan "Service was originally started, restarting service: $($service.Name)" 
  61.             $service.StartService() 
  62.         
  63.         else { Write-Host -ForegroundColor Cyan "Service was not originally started, not restarting service: $($service.Name)"
  64.     
  65.     else { ReturnCodeSwitch $returnCode
  66.  
  67. function ReturnCodeSwitch ([int]$returnCode) { 
  68.     switch ($returnCode) { 
  69.         1 {Write-Host -ForegroundColor Red "Not Supported"; break
  70.         2 {Write-Host -ForegroundColor Red "Access Denied"; break
  71.         3 {Write-Host -ForegroundColor Red "Dependent Services Running"; break
  72.         4 {Write-Host -ForegroundColor Red "Invalid Service Control"; break
  73.         5 {Write-Host -ForegroundColor Red "Service Cannot Accept Control"; break
  74.         6 {Write-Host -ForegroundColor Red "Service Not Active"; break
  75.         7 {Write-Host -ForegroundColor Red "Service Request Timeout"; break
  76.         8 {Write-Host -ForegroundColor Red "Unknown Failure"; break
  77.         9 {Write-Host -ForegroundColor Red "Path Not Found"; break
  78.         10 {Write-Host -ForegroundColor Red "Service Already Running"; break
  79.         11 {Write-Host -ForegroundColor Red "Service Database Locked"; break
  80.         12 {Write-Host -ForegroundColor Red "Service Dependency Deleted"; break
  81.         13 {Write-Host -ForegroundColor Red "Service Dependency Failure"; break
  82.         14 {Write-Host -ForegroundColor Red "Service Disabled"; break
  83.         15 {Write-Host -ForegroundColor Red "Service Logon Failure"; break
  84.         16 {Write-Host -ForegroundColor Red "Service Marked For Deletion"; break
  85.         17 {Write-Host -ForegroundColor Red "Service No Thread"; break
  86.         18 {Write-Host -ForegroundColor Red "Status Circular Dependency"; break
  87.         19 {Write-Host -ForegroundColor Red "Status Duplicate Name"; break
  88.         20 {Write-Host -ForegroundColor Red "Status Invalid Name"; break
  89.         21 {Write-Host -ForegroundColor Red "Status Invalid Parameter"; break
  90.         22 {Write-Host -ForegroundColor Red "Status Invalid Service Account"; break
  91.         23 {Write-Host -ForegroundColor Red "Status Service Exists"; break
  92.         24 {Write-Host -ForegroundColor Red "Service Already Paused"; break
  93.     
  94.  
  95. # ============================================================================================== 
  96. # NAME:            ChangeServiceAccountHelp 
  97. # AUTHOR:        Brian Hagerty 
  98. # DATE:            03/03/2009 
  99. # COMMENT:         Help function for the Change-ServiceAcct function 
  100. # MODIFIED:         
  101. # ============================================================================================== 
  102.  
  103. function ChangeServiceAccountHelp { 
  104.     Write-Host -ForegroundColor Yellow "`n`nPURPOSE: Pipeline function! Accepts computer names from pipeline & changes specific properties for the specified service account." 
  105.     Write-Host -ForegroundColor Cyan "`nSYNTAX: $computername_array [[string]computerName] | Change-ServiceAcct [string]ServiceName [[string]DisplayName [string]PathName [byte]ServiceType [byte]ErrorControl [string]StartMode [boolean]DesktopInteract [string]StartName [string]StartPassword [string]LoadOrderGroup [string[]]LoadOrderGroupDependencies [string[]]ServiceDepencies" 
  106.      
  107.     Write-Host -ForegroundColor Cyan "`n`nDisplayName :" 
  108.     Write-Host -ForegroundColor Green "The display name of the service. This string has a maximum length of 256 characters. The name is case-preserved in the service control manager. DisplayName comparisons are always case-insensitive." 
  109.     Write-Host -ForegroundColor Yellow "Example :  ""Atdisk""" 
  110.      
  111.     Write-Host -ForegroundColor Cyan "`n`nPathName :" 
  112.     Write-Host -ForegroundColor Green "The fully-qualified path to the executable file that implements the service." 
  113.     Write-Host -ForegroundColor Yellow "Example :  ""\SystemRoot\System32\drivers\afd.sys""" 
  114.      
  115.     Write-Host -ForegroundColor Cyan "`n`nServiceType:" 
  116.     Write-Host -ForegroundColor Green "The type of services provided to processes that call them." 
  117.     Write-Host -ForegroundColor Yellow "`nValues [Value - Meaning]:" 
  118.     Write-Host -ForegroundColor Yellow "------------------------------------------" 
  119.     Write-Host -ForegroundColor Yellow "10x1 - Kernel Driver" 
  120.     Write-Host -ForegroundColor Yellow "20x2 - File System Driver" 
  121.     Write-Host -ForegroundColor Yellow "40x4 - Adapter" 
  122.     Write-Host -ForegroundColor Yellow "80x8 - Recognizer Driver" 
  123.     Write-Host -ForegroundColor Yellow "160x10 - Own Process" 
  124.     Write-Host -ForegroundColor Yellow "320x20 - Share Process" 
  125.     Write-Host -ForegroundColor Yellow "2560x100 - Interactive Process" 
  126.      
  127.     Write-Host -ForegroundColor Cyan "`n`nErrorControl :" 
  128.     Write-Host -ForegroundColor Green "Severity of the error if this service fails to start during startup. The value indicates the action taken by the startup program if failure occurs. All errors are logged by the system." 
  129.     Write-Host -ForegroundColor Yellow "`nValues [Value - Meaning]:" 
  130.     Write-Host -ForegroundColor Yellow "------------------------------------------" 
  131.     Write-Host -ForegroundColor Yellow "0 - Ignore. User is not notified." 
  132.     Write-Host -ForegroundColor Yellow "1 - Normal. User is notified." 
  133.     Write-Host -ForegroundColor Yellow "2 - Severe. System is restarted with the last-known-good configuration." 
  134.     Write-Host -ForegroundColor Yellow "3 - Critical. System attempts to restart with a good configuration." 
  135.      
  136.      
  137.     Write-Host -ForegroundColor Cyan "`n`nStartMode:"  
  138.     Write-Host -ForegroundColor Green "Start mode of the Windows base service." 
  139.     Write-Host -ForegroundColor Yellow "`nValues [Value - Meaning]:" 
  140.     Write-Host -ForegroundColor Yellow "------------------------------------------" 
  141.     Write-Host -ForegroundColor Yellow "Boot - Device driver started by the operating system loader." 
  142.     Write-Host -ForegroundColor Yellow "System - Device driver started by the operating system initialization process. Valid only for driver services." 
  143.     Write-Host -ForegroundColor Yellow "Automatic - Service to be started automatically by the service control manager during system startup." 
  144.     Write-Host -ForegroundColor Yellow "Manual - Service to be started by the service control manager when a process calls the StartService method." 
  145.     Write-Host -ForegroundColor Yellow "Disabled - Service that can no longer be started." 
  146.      
  147.     Write-Host -ForegroundColor Cyan "`n`nDesktopInteract:" 
  148.     Write-Host -ForegroundColor Green "If true, the service can create or communicate with a window on the desktop." 
  149.      
  150.     Write-Host -ForegroundColor Cyan "`n`nStartName:" 
  151.     Write-Host -ForegroundColor Green "Account name the service runs under. Depending on the service type, the account name may be in the form of DomainName\Username or .\Username. The service process will be logged using one of these two forms when it runs. If the account belongs to the built-in domain, .\Username can be specified. If NULL is specified, the service will be logged on as the LocalSystem account. For kernel or system-level drivers, StartName contains the driver object name (that is, \FileSystem\rdr or \Driver\Xns) that the input and output (I/O) system uses to load the device driver. If NULL is specified, the driver runs with a default object name created by the I/O system based on the service name, for example, ""DWDOM\Admin"". You also can use the User Principal Name (UPN) format to specify the StartName, for example, Username@DomainName." 
  152.      
  153.     Write-Host -ForegroundColor Cyan "`n`nStartPassword:" 
  154.     Write-Host -ForegroundColor Green "Password to the account name specified by the StartName parameter. Specify NULL if you are not changing the password. Specify an empty string if the service has no password. (Note:  When changing a service from a local system to a network, or from a network to a local system, StartPassword must be an empty string ("""") and not NULL.)" 
  155.      
  156.     Write-Host -ForegroundColor Cyan "`n`nLoadOrderGroup:" 
  157.     Write-Host -ForegroundColor Green "Group name that it is associated with. Load order groups are contained in the system registry, and determine the sequence in which services are loaded into the operating system. If the pointer is NULL, or if it points to an empty string, the service does not belong to a group. Dependencies between groups should be listed in the LoadOrderGroupDependencies parameter. Services in the load-ordering group list are started first, followed by services in groups not in the load-ordering group list, followed by services that do not belong to a group. The system registry has a list of load ordering groups located at HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ServiceGroupOrder." 
  158.      
  159.     Write-Host -ForegroundColor Cyan "`n`nLoadOrderGroupDependencies:" 
  160.     Write-Host -ForegroundColor Green "List of load-ordering groups that must start before this service starts. The array is doubly null-terminated. If the pointer is NULL, or if it points to an empty string, the service has no dependencies. Group names must be prefixed by the SC_GROUP_IDENTIFIER (defined in the Winsvc.h file) character to differentiate them from service names because services and service groups share the same name space. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all of the members of the group." 
  161.      
  162.     Write-Host -ForegroundColor Cyan "`n`nServiceDependencies:" 
  163.     Write-Host -ForegroundColor Green "List that contains the names of services that must start before this service starts. The array is doubly NULL-terminated. If the pointer is NULL, or if it points to an empty string, the service has no dependencies. Dependency on a service indicates that this service can run only if the service it depends on is running." 
  164.     Write-Host 

Accepts computer names from pipeline & changes specific properties for the specified service account.

NTRIGHTS Utility is used to grant a Service Account logon privileges.

NTRIGHTS Utility is part of the Windows Server 2003 Resource Kit

Copyright 2012 PowerShell.com. All rights reserved.