protected override void BeginProcessing() { Diagnostics.Assert(!String.IsNullOrEmpty(Name), "null ServiceName"); Diagnostics.Assert(!String.IsNullOrEmpty(BinaryPathName), "null BinaryPathName"); // confirm the operation first // this is always false if WhatIf is set if (!ShouldProcessServiceOperation(DisplayName ?? "", Name)) { return; } // Connect to the service controller NakedWin32Handle hScManager = IntPtr.Zero; NakedWin32Handle hService = IntPtr.Zero; IntPtr password = IntPtr.Zero; try { hScManager = NativeMethods.OpenSCManagerW( null, null, NativeMethods.SC_MANAGER_CONNECT | NativeMethods.SC_MANAGER_CREATE_SERVICE ); if (IntPtr.Zero == hScManager) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( Name, DisplayName, Name, exception, "CouldNotNewService", ServiceResources.CouldNotNewService, ErrorCategory.PermissionDenied); return; } DWORD dwStartType = NativeMethods.SERVICE_AUTO_START; switch (StartupType) { case ServiceStartMode.Automatic: dwStartType = NativeMethods.SERVICE_AUTO_START; break; case ServiceStartMode.Manual: dwStartType = NativeMethods.SERVICE_DEMAND_START; break; case ServiceStartMode.Disabled: dwStartType = NativeMethods.SERVICE_DISABLED; break; default: Diagnostics.Assert( ((ServiceStartMode)(-1)) == StartupType, "bad StartupType"); break; } // set up the double-null-terminated lpDependencies parameter IntPtr lpDependencies = IntPtr.Zero; if (null != DependsOn) { int numchars = 1; // final null foreach (string dependedOn in DependsOn) { numchars += dependedOn.Length + 1; } char[] doubleNullArray = new char[numchars]; int pos = 0; foreach (string dependedOn in DependsOn) { Array.Copy( dependedOn.ToCharArray(), 0, doubleNullArray, pos, dependedOn.Length ); pos += dependedOn.Length; doubleNullArray[pos++] = (char)0; // null terminator } doubleNullArray[pos++] = (char)0; // double-null terminator Diagnostics.Assert(pos == numchars, "lpDependencies build error"); lpDependencies = Marshal.AllocHGlobal( numchars * Marshal.SystemDefaultCharSize); Marshal.Copy(doubleNullArray, 0, lpDependencies, numchars); } // set up the Credential parameter string username = null; if (null != Credential) { username = Credential.UserName; password = ClrFacade.SecureStringToCoTaskMemUnicode(Credential.Password); } // Create the service hService = NativeMethods.CreateServiceW( hScManager, Name, DisplayName, NativeMethods.SERVICE_CHANGE_CONFIG, NativeMethods.SERVICE_WIN32_OWN_PROCESS, dwStartType, NativeMethods.SERVICE_ERROR_NORMAL, BinaryPathName, null, null, lpDependencies, username, password ); if (IntPtr.Zero == hService) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( Name, DisplayName, Name, exception, "CouldNotNewService", ServiceResources.CouldNotNewService, ErrorCategory.PermissionDenied); return; } // Set the service description NativeMethods.SERVICE_DESCRIPTIONW sd = new NativeMethods.SERVICE_DESCRIPTIONW(); sd.lpDescription = Description; int size = Marshal.SizeOf(sd); IntPtr buffer = Marshal.AllocCoTaskMem(size); Marshal.StructureToPtr(sd, buffer, false); bool succeeded = NativeMethods.ChangeServiceConfig2W( hService, NativeMethods.SERVICE_CONFIG_DESCRIPTION, buffer); if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( Name, DisplayName, Name, exception, "CouldNotNewServiceDescription", ServiceResources.CouldNotNewServiceDescription, ErrorCategory.PermissionDenied); } // write the ServiceController for the new service using (ServiceController service = new ServiceController(Name)) // ensure dispose { WriteObject(service); } } finally { if (IntPtr.Zero != password) { Marshal.ZeroFreeCoTaskMemUnicode(password); } if (IntPtr.Zero != hService) { bool succeeded = NativeMethods.CloseServiceHandle(hService); if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( Name, DisplayName, Name, exception, "CouldNotNewServiceDescription", ServiceResources.CouldNotNewServiceDescription, ErrorCategory.PermissionDenied); } } if (IntPtr.Zero != hScManager) { bool succeeded = NativeMethods.CloseServiceHandle(hScManager); if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( Name, DisplayName, Name, exception, "CouldNotNewServiceDescription", ServiceResources.CouldNotNewServiceDescription, ErrorCategory.PermissionDenied); } } } }
protected override void ProcessRecord() { ServiceController service = null; string ServiceComputerName = null; foreach (string computer in ComputerName) { bool objServiceShouldBeDisposed = false; try { if (_ParameterSetName.Equals("InputObject", StringComparison.OrdinalIgnoreCase) && InputObject != null) { service = InputObject; Name = service.ServiceName; ServiceComputerName = service.MachineName; //computer = service.MachineName; objServiceShouldBeDisposed = false; } else { ServiceComputerName = computer; service = new ServiceController(serviceName, ServiceComputerName); objServiceShouldBeDisposed = true; } Diagnostics.Assert(!String.IsNullOrEmpty(Name), "null ServiceName"); // "new ServiceController" will succeed even if // there is no such service. This checks whether // the service actually exists. string unusedByDesign = service.DisplayName; } catch (ArgumentException ex) { //cannot use WriteNonterminatingError as service is null ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.ObjectNotFound, computer); WriteError(er); continue; } catch (InvalidOperationException ex) { //cannot use WriteNonterminatingError as service is null ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.ObjectNotFound, computer); WriteError(er); continue; } try // In finally we ensure dispose, if object not pipelined. { // confirm the operation first // this is always false if WhatIf is set if (!ShouldProcessServiceOperation(service)) { continue; } NakedWin32Handle hScManager = IntPtr.Zero; NakedWin32Handle hService = IntPtr.Zero; try { hScManager = NativeMethods.OpenSCManagerW( ServiceComputerName, null, NativeMethods.SC_MANAGER_CONNECT ); if (IntPtr.Zero == hScManager) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( service, ServiceComputerName, exception, "ComputerAccessDenied", ServiceResources.ComputerAccessDenied, ErrorCategory.PermissionDenied); continue; } hService = NativeMethods.OpenServiceW( hScManager, Name, NativeMethods.SERVICE_CHANGE_CONFIG ); if (IntPtr.Zero == hService) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( service, exception, "CouldNotSetService", ServiceResources.CouldNotSetService, ErrorCategory.PermissionDenied); continue; } // modify startup type or display name if (!String.IsNullOrEmpty(DisplayName) || (ServiceStartMode)(-1) != StartupType) { DWORD dwStartType = NativeMethods.SERVICE_NO_CHANGE; switch (StartupType) { case ServiceStartMode.Automatic: dwStartType = NativeMethods.SERVICE_AUTO_START; break; case ServiceStartMode.Manual: dwStartType = NativeMethods.SERVICE_DEMAND_START; break; case ServiceStartMode.Disabled: dwStartType = NativeMethods.SERVICE_DISABLED; break; default: Diagnostics.Assert( ((ServiceStartMode)(-1)) == StartupType, "bad StartupType"); break; } bool succeeded = NativeMethods.ChangeServiceConfigW( hService, NativeMethods.SERVICE_NO_CHANGE, dwStartType, NativeMethods.SERVICE_NO_CHANGE, null, null, IntPtr.Zero, null, null, IntPtr.Zero, DisplayName ); if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( service, exception, "CouldNotSetService", ServiceResources.CouldNotSetService, ErrorCategory.PermissionDenied); continue; } } // modify startup type or display name NativeMethods.SERVICE_DESCRIPTIONW sd = new NativeMethods.SERVICE_DESCRIPTIONW(); sd.lpDescription = Description; int size = Marshal.SizeOf(sd); IntPtr buffer = Marshal.AllocCoTaskMem(size); Marshal.StructureToPtr(sd, buffer, false); bool status = NativeMethods.ChangeServiceConfig2W( hService, NativeMethods.SERVICE_CONFIG_DESCRIPTION, buffer); if (!status) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( service, exception, "CouldNotSetServiceDescription", ServiceResources.CouldNotSetServiceDescription, ErrorCategory.PermissionDenied); } //Addition by v-ramch Mar 11 2008 //if Status parameter specified do the necessary action //to bring about the desired result if (!string.IsNullOrEmpty(Status)) { if (Status.Equals("Running", StringComparison.OrdinalIgnoreCase)) { if (!service.Status.Equals(ServiceControllerStatus.Running)) { if (service.Status.Equals(ServiceControllerStatus.Paused)) //resume service DoResumeService(service); else //start service DoStartService(service); } } else if (Status.Equals("Stopped", StringComparison.CurrentCultureIgnoreCase)) { if (!service.Status.Equals(ServiceControllerStatus.Stopped)) { //check for the dependent services as set-service dont have force parameter ServiceController[] dependentServices = service.DependentServices; if ((dependentServices != null) && (dependentServices.Length > 0)) { WriteNonTerminatingError(service, null, "ServiceHasDependentServicesNoForce", ServiceResources.ServiceHasDependentServicesNoForce, ErrorCategory.InvalidOperation); continue; } ServiceController[] servicedependedon = service.ServicesDependedOn; if ((servicedependedon != null) && (servicedependedon.Length > 0)) { WriteNonTerminatingError(service, null, "ServiceIsDependentOnNoForce", ServiceResources.ServiceIsDependentOnNoForce, ErrorCategory.InvalidOperation); continue; } //stop service,give the force parameter always true as we have already checked for the dependent services //Specify NoWait parameter as always false since we are not adding this switch to this cmdlet DoStopService(service, true, true); } } else if (Status.Equals("Paused", StringComparison.CurrentCultureIgnoreCase)) { if (!service.Status.Equals(ServiceControllerStatus.Paused)) //pause service DoPauseService(service); } } if (PassThru.IsPresent) { //to display the service,refreshing the service would not show the display name after updating ServiceController displayservice = new ServiceController(Name, ServiceComputerName); WriteObject(displayservice); } } finally { if (IntPtr.Zero != hService) { bool succeeded = NativeMethods.CloseServiceHandle(hService); if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( service, exception, "CouldNotSetServiceDescription", ServiceResources.CouldNotSetServiceDescription, ErrorCategory.PermissionDenied); } } if (IntPtr.Zero != hScManager) { bool succeeded = NativeMethods.CloseServiceHandle(hScManager); if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); Win32Exception exception = new Win32Exception(lastError); WriteNonTerminatingError( service, exception, "CouldNotSetServiceDescription", ServiceResources.CouldNotSetServiceDescription, ErrorCategory.PermissionDenied); } } } // finally } //End try finally { if (objServiceShouldBeDisposed) { service.Dispose(); } } }//end for }
protected override void ProcessRecord() { ServiceController serviceController = null; string machineName = null; string[] strArrays = this.computername; for (int i = 0; i < (int)strArrays.Length; i++) { string str = strArrays[i]; bool flag = false; try { if (!base._ParameterSetName.Equals("InputObject", StringComparison.OrdinalIgnoreCase) || this.inputobject == null) { machineName = str; serviceController = new ServiceController(this.serviceName, machineName); flag = true; } else { serviceController = this.inputobject; this.Name = serviceController.ServiceName; machineName = serviceController.MachineName; flag = false; } } catch (ArgumentException argumentException1) { ArgumentException argumentException = argumentException1; ErrorRecord errorRecord = new ErrorRecord(argumentException, "ArgumentException", ErrorCategory.ObjectNotFound, str); base.WriteError(errorRecord); goto Label0; } catch (InvalidOperationException invalidOperationException1) { InvalidOperationException invalidOperationException = invalidOperationException1; ErrorRecord errorRecord1 = new ErrorRecord(invalidOperationException, "InvalidOperationException", ErrorCategory.ObjectNotFound, str); base.WriteError(errorRecord1); goto Label0; } using (serviceController) { if (!flag) { if (base.ShouldProcessServiceOperation(serviceController)) { IntPtr zero = IntPtr.Zero; IntPtr intPtr = IntPtr.Zero; try { zero = NativeMethods.OpenSCManagerW(machineName, null, 1); if (IntPtr.Zero != zero) { intPtr = NativeMethods.OpenServiceW(zero, this.Name, 2); if (IntPtr.Zero != intPtr) { if (!string.IsNullOrEmpty(this.DisplayName) || (ServiceStartMode.Manual | ServiceStartMode.Automatic | ServiceStartMode.Disabled) != this.StartupType) { uint num = 0; ServiceStartMode startupType = this.StartupType; switch (startupType) { case ServiceStartMode.Automatic: { num = 2; break; } case ServiceStartMode.Manual: { num = 3; break; } case ServiceStartMode.Disabled: { num = 4; break; } } bool flag1 = NativeMethods.ChangeServiceConfigW(intPtr, 0, num, 0, null, null, IntPtr.Zero, null, null, IntPtr.Zero, this.DisplayName); if (!flag1) { int lastWin32Error = Marshal.GetLastWin32Error(); Win32Exception win32Exception = new Win32Exception(lastWin32Error); base.WriteNonTerminatingError(serviceController, win32Exception, "CouldNotSetService", ServiceResources.CouldNotSetService, ErrorCategory.PermissionDenied); goto Label0; } } NativeMethods.SERVICE_DESCRIPTIONW description = new NativeMethods.SERVICE_DESCRIPTIONW(); description.lpDescription = this.Description; int num1 = Marshal.SizeOf(description); IntPtr intPtr1 = Marshal.AllocCoTaskMem(num1); Marshal.StructureToPtr(description, intPtr1, false); bool flag2 = NativeMethods.ChangeServiceConfig2W(intPtr, 1, intPtr1); if (!flag2) { int lastWin32Error1 = Marshal.GetLastWin32Error(); Win32Exception win32Exception1 = new Win32Exception(lastWin32Error1); base.WriteNonTerminatingError(serviceController, win32Exception1, "CouldNotSetServiceDescription", ServiceResources.CouldNotSetServiceDescription, ErrorCategory.PermissionDenied); } if (!string.IsNullOrEmpty(this.Status)) { if (!this.Status.Equals("Running", StringComparison.OrdinalIgnoreCase)) { if (!this.Status.Equals("Stopped", StringComparison.CurrentCultureIgnoreCase)) { if (this.Status.Equals("Paused", StringComparison.CurrentCultureIgnoreCase) && !serviceController.Status.Equals(ServiceControllerStatus.Paused)) { base.DoPauseService(serviceController); } } else { if (!serviceController.Status.Equals(ServiceControllerStatus.Stopped)) { ServiceController[] dependentServices = serviceController.DependentServices; if (dependentServices == null || (int)dependentServices.Length <= 0) { ServiceController[] servicesDependedOn = serviceController.ServicesDependedOn; if (servicesDependedOn == null || (int)servicesDependedOn.Length <= 0) { base.DoStopService(serviceController, true); } else { base.WriteNonTerminatingError(serviceController, null, "ServiceIsDependentOnNoForce", ServiceResources.ServiceIsDependentOnNoForce, ErrorCategory.InvalidOperation); goto Label0; } } else { base.WriteNonTerminatingError(serviceController, null, "ServiceHasDependentServicesNoForce", ServiceResources.ServiceHasDependentServicesNoForce, ErrorCategory.InvalidOperation); goto Label0; } } } } else { if (!serviceController.Status.Equals(ServiceControllerStatus.Running)) { if (!serviceController.Status.Equals(ServiceControllerStatus.Paused)) { base.DoStartService(serviceController); } else { base.DoResumeService(serviceController); } } } } SwitchParameter passThru = base.PassThru; if (passThru.IsPresent) { ServiceController serviceController1 = new ServiceController(this.Name, machineName); base.WriteObject(serviceController1); } } else { int lastWin32Error2 = Marshal.GetLastWin32Error(); Win32Exception win32Exception2 = new Win32Exception(lastWin32Error2); base.WriteNonTerminatingError(serviceController, win32Exception2, "CouldNotSetService", ServiceResources.CouldNotSetService, ErrorCategory.PermissionDenied); goto Label0; } } else { int num2 = Marshal.GetLastWin32Error(); Win32Exception win32Exception3 = new Win32Exception(num2); base.WriteNonTerminatingError(serviceController, machineName, win32Exception3, "ComputerAccessDenied", ServiceResources.ComputerAccessDenied, ErrorCategory.PermissionDenied); goto Label0; } } finally { if (IntPtr.Zero != intPtr) { bool flag3 = NativeMethods.CloseServiceHandle(intPtr); if (!flag3) { int lastWin32Error3 = Marshal.GetLastWin32Error(); Win32Exception win32Exception4 = new Win32Exception(lastWin32Error3); base.WriteNonTerminatingError(serviceController, win32Exception4, "CouldNotSetServiceDescription", ServiceResources.CouldNotSetServiceDescription, ErrorCategory.PermissionDenied); } } if (IntPtr.Zero != zero) { bool flag4 = NativeMethods.CloseServiceHandle(zero); if (!flag4) { int num3 = Marshal.GetLastWin32Error(); Win32Exception win32Exception5 = new Win32Exception(num3); base.WriteNonTerminatingError(serviceController, win32Exception5, "CouldNotSetServiceDescription", ServiceResources.CouldNotSetServiceDescription, ErrorCategory.PermissionDenied); } } } } } } Label0: continue; } }
protected override void BeginProcessing() { string displayName; NewServiceCommand newServiceCommand = this; if (this.DisplayName == null) { displayName = ""; } else { displayName = this.DisplayName; } if (newServiceCommand.ShouldProcessServiceOperation(displayName, this.Name)) { IntPtr zero = IntPtr.Zero; IntPtr intPtr = IntPtr.Zero; IntPtr globalAllocUnicode = IntPtr.Zero; try { zero = NativeMethods.OpenSCManagerW(null, null, 3); if (IntPtr.Zero != zero) { uint num = 2; ServiceStartMode startupType = this.StartupType; switch (startupType) { case ServiceStartMode.Automatic: { num = 2; break; } case ServiceStartMode.Manual: { num = 3; break; } case ServiceStartMode.Disabled: { num = 4; break; } } IntPtr zero1 = IntPtr.Zero; if (this.DependsOn != null) { int length = 1; string[] dependsOn = this.DependsOn; for (int i = 0; i < (int)dependsOn.Length; i++) { string str = dependsOn[i]; length = length + str.Length + 1; } char[] chrArray = new char[length]; int length1 = 0; string[] strArrays = this.DependsOn; for (int j = 0; j < (int)strArrays.Length; j++) { string str1 = strArrays[j]; Array.Copy(str1.ToCharArray(), 0, chrArray, length1, str1.Length); length1 = length1 + str1.Length; int num1 = length1; length1 = num1 + 1; chrArray[num1] = '\0'; } int num2 = length1; chrArray[num2] = '\0'; zero1 = Marshal.AllocHGlobal(length * Marshal.SystemDefaultCharSize); Marshal.Copy(chrArray, 0, zero1, length); } string userName = null; if (this.Credential != null) { userName = this.Credential.UserName; globalAllocUnicode = Marshal.SecureStringToGlobalAllocUnicode(this.Credential.Password); } intPtr = NativeMethods.CreateServiceW(zero, this.Name, this.DisplayName, 2, 16, num, 1, this.BinaryPathName, null, null, zero1, userName, globalAllocUnicode); if (IntPtr.Zero != intPtr) { NativeMethods.SERVICE_DESCRIPTIONW description = new NativeMethods.SERVICE_DESCRIPTIONW(); description.lpDescription = this.Description; int num3 = Marshal.SizeOf(description); IntPtr intPtr1 = Marshal.AllocCoTaskMem(num3); Marshal.StructureToPtr(description, intPtr1, false); bool flag = NativeMethods.ChangeServiceConfig2W(intPtr, 1, intPtr1); if (!flag) { int lastWin32Error = Marshal.GetLastWin32Error(); Win32Exception win32Exception = new Win32Exception(lastWin32Error); base.WriteNonTerminatingError(this.Name, this.DisplayName, this.Name, win32Exception, "CouldNotNewServiceDescription", ServiceResources.CouldNotNewServiceDescription, ErrorCategory.PermissionDenied); } using (ServiceController serviceController = new ServiceController(this.Name)) { base.WriteObject(serviceController); } } else { int lastWin32Error1 = Marshal.GetLastWin32Error(); Win32Exception win32Exception1 = new Win32Exception(lastWin32Error1); base.WriteNonTerminatingError(this.Name, this.DisplayName, this.Name, win32Exception1, "CouldNotNewService", ServiceResources.CouldNotNewService, ErrorCategory.PermissionDenied); } } else { int lastWin32Error2 = Marshal.GetLastWin32Error(); Win32Exception win32Exception2 = new Win32Exception(lastWin32Error2); base.WriteNonTerminatingError(this.Name, this.DisplayName, this.Name, win32Exception2, "CouldNotNewService", ServiceResources.CouldNotNewService, ErrorCategory.PermissionDenied); } } finally { if (IntPtr.Zero != globalAllocUnicode) { Marshal.ZeroFreeGlobalAllocUnicode(globalAllocUnicode); } if (IntPtr.Zero != intPtr) { bool flag1 = NativeMethods.CloseServiceHandle(intPtr); if (!flag1) { int lastWin32Error3 = Marshal.GetLastWin32Error(); Win32Exception win32Exception3 = new Win32Exception(lastWin32Error3); base.WriteNonTerminatingError(this.Name, this.DisplayName, this.Name, win32Exception3, "CouldNotNewServiceDescription", ServiceResources.CouldNotNewServiceDescription, ErrorCategory.PermissionDenied); } } if (IntPtr.Zero != zero) { bool flag2 = NativeMethods.CloseServiceHandle(zero); if (!flag2) { int lastWin32Error4 = Marshal.GetLastWin32Error(); Win32Exception win32Exception4 = new Win32Exception(lastWin32Error4); base.WriteNonTerminatingError(this.Name, this.DisplayName, this.Name, win32Exception4, "CouldNotNewServiceDescription", ServiceResources.CouldNotNewServiceDescription, ErrorCategory.PermissionDenied); } } } return; } else { return; } }