How to create a servicename using powershell - powershell

I am trying to create a servicename that should be displayed when I go to "service.msc", powershell script is not able to create.
I tried the following code but its not able to create the service. I am running this as a "Administrator"
$serviceName="RSCDsvc"
$serviceDisplayName="BMC BladeLogic Server Automation RSCD Agent"
$serviceDescription="BMC BladeLogic Server Automation Remote System Call Daemon"
$serviceExecutable="RSCDsvc.exe"
LogWrite $bsaLog "Installing service.."
$binaryPath="C:\Program Files\BMC Software\BladeLogic\RSCD\RSCDsvc.exe"
New-Service -name $serviceName -DisplayName $serviceDisplayName -binaryPathName $binaryPath -StartupType Automatic -Description $serviceDescription
Start-Service -Name $serviceName
Get-Service $serviceName
LogWrite $bsaLog "Service Installed.."
I want to see the servicename when I type "services.msc" I should be able to see "RSCDsvc" with display "BMC Bladelogic Server Automation RSCD Agent"
When I run these commands in the powershell prompt individually I get the following error, I could see this service running when I go to taskmanager and go to "Details" tab I could see the service, but not when I go to "services.msc"
New-Service : Service 'BMC BladeLogic Server Automation RSCD Agent (RSCDsvc)' cannot be created due to the following error: The
specified service already exists
At line:1 char:1
+ New-Service -name $serviceName -DisplayName $serviceDisplayName -bina ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (RSCDsvc:String) [New-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotNewService,Microsoft.PowerShell.Commands.NewServiceCommand

Related

Running Powershell script using inline admin credentials to start and stop windows services

I have access as an admin on a machine and I have to Start, Stop and Restart some of the window services using the Powershell script. We don't want to have UAC prompt while running the script because only one user would have access to that machine. Also due to some specific requirements, we have to have run that script file by adding the admin credentials inside it.
Along with other solutions I have tried so far, the one close to what I am looking for is as follows
$username = "Domain\user"
$password = ConvertTo-SecureString "myPassword" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
Set-Service -Name Spooler -Status Running -PassThru -Credential $psCred
But I am getting following error.
Set-Service : A parameter cannot be found that matches parameter name
'Credential'. At line:6 char:53
+ ... t-Service -Name Spooler -Status Running -PassThru -Credential $psCred
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Update 1 (Trying suggestion)
Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername myComputerName
[myComputerName] Connecting to remote server myComputerName failed
with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command on the destination to analyze
and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (myComputerName:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken
Update 2
I had to enabled PSRemoting on machine using command Enable-PSRemoting -Force -SkipNetworkProfileCheck so Invoke-Command can execute but after repeating the command Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername localhost I got following error
[localhost] Connecting to remote server localhost failed with the
following error message : Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Running the same set of command in elevated powershell window is working fine.
Can you please guide me in the right direction considering I am newbie in the Powershell world.
As mentioned in the official documentation of Set-Service
Can you try like this?
$Cred = Get-Credential
$hostname = "$env:computername.$env:userdnsdomain"
Write-Host $hostname
Invoke-Command -ComputerName $hostname -Credential $Cred -ScriptBlock{ Start-Service -Name Spooler}
Also if you don't want to prompt for the credentials then you can store the credentials in the Windows credentials manager and get it from their in your PowerShell script. Refer to this answer for using credential manager with PowerShell

Not able to run PowerShell on Jenkins

I am running a PowerShell script which will stop a service on remote machine. When I am running it in PowerShell ISE then it is running fine. But when I am trying to run it from Jenkins hosted on my local machine it is giving me an error.
$SQL_agent="SQLSERVERAGENT"
$SQL_server="MSSQLSERVER"
$SQL_Agent_Service = Get-Service -Name $SQL_agent -ComputerName 192.168.48.44
$SQL_Server_Service = Get-Service -Name $SQL_server -ComputerName 192.168.48.44
Stop-Service -InputObject $SQL_Agent_Service
log("[SQLSERVERAGENT] shutdown complete.");
Stop-Service -InputObject $SQL_Server_Service
log("[MSSQLSERVER] shutdown complete.");
I am getting following error while running it from jenkins (jenkins is running on my local machine),
<pre>
D:\Eclipse_Repository\self_repo\jmallick\remote_db_backup.ps1:42 char:22
+ ... ent_Service = Get-Service -Name $SQL_agent -ComputerName 192.168.48.44
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (SQLSERVERAGENT:String) [Get-Ser
vice], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.
Commands.GetServiceCommand
Get-Service : Cannot find any service with service name 'MSSQLSERVER'.At
D:\Eclipse_Repository\self_repo\jmallick\remote_db_backup.ps1:43 char:23
+ ... er_Service = Get-Service -Name $SQL_server -ComputerName 192.168.48.44
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (MSSQLSERVER:String) [Get-Servic
e], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.
Commands.GetServiceCommand
</pre>
Any thoughts on this?
It looks like Jenkins is not running under the same account as of MSSQLSERVER
To change account for jenkins or MSSQLSERVER service
Follow go to services
right click on Jenkins services and select Properties.
Go to Log On tab
Click on This Account
In browse dialog select the user account you want o run Jenkins or Database server in

Set-Service: Cannot stop service because it is dependent on other services

When I run the following command:
Set-Service -ComputerName appserver -Name MyService -Status Stopped
I get an error message:
Set-Service : Cannot stop service 'My Service (MyService)' because it is
dependent on other services.
At line:1 char:12
+ Set-Service <<<< -ComputerName appserver -Name MyService -Status Stopped
+ CategoryInfo : InvalidOperation: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], ServiceCommandException
+ FullyQualifiedErrorId : ServiceIsDependentOnNoForce,Microsoft.PowerShell.Commands.SetServiceCommand
I can stop the service from the services.msc GUI, and I can start the service with Set-Service, but I can't stop it again.
It is true that the service depends on some other services, but I don't understand why that would prevent me from stopping it—nothing else depends on it.
The Set-Service cmdlet is for changing the configuration of a service. That you can use it to stop a service by changing its status is just coincidental. Use the Stop-Service cmdlet for stopping services. It allows you to stop dependent services as well via the parameter -Force. You'll need to retrieve the service object with Get-Service first, though, since Stop-Service doesn't have a parameter -ComputerName.
Get-Service -Computer appserver -Name MyService | Stop-Service -Force
I eventually resolved this problem with the following code, which calls sc to stop the service and then waits for it to finish stopping. This achieves the same result as expected from Set-Service -Status Stopped; that is, when it returns the service has been stopped. (sc on its own starts to stop the service, but does not wait until it has finished stopping.)
Start-Process "$env:WINDIR\system32\sc.exe" \\APPSERVER,stop,MyService -NoNewWindow -Wait
while ((Get-Service -ComputerName APPSERVER -Name MyService |
Select -ExpandProperty Status) -ne 'Stopped') {
Write-Host "Waiting for service to stop..."
Start-Sleep -Seconds 10
}

Azure Powershell to stop VM's in a subscription

I am new to Powershell, and to be specific entirely new to Azure Powershell. I need to create a powershell script to switch off all the VM's found on a subscription. I guess this needs to be done with the help of management certificate. But not sure where to start. I just done some simple lines of code to list all VM's as shown below:
Add-AzureAccount -Environment "AzureCloud"
$subscription = "my-sub-scri-ption"
Select-AzureSubscription -Current "SubName"
Set-AzureSubscription -SubscriptionName "SubName"
Get-AzureVM -ServiceName "VM1"
The output recieved is "Get-AzureVM : Value cannot be null.
Parameter name: subscriptionId".
Can someone please help me in this regard?
**EDIT:**
The powershell script which I am using is given below:
Add-AzureAccount -Environment "AzureCloud"
Set-AzureSubscription -SubscriptionName "My Subs"
$serviceName = "Service01"
$vmName = "Service01"
Get-AzureVM | Stop-AzureVM -Force
Though while running it shows script execution is successful, I can see still that vm is powered on. Please note that the serviceName and vmName is same in my case. Anything wrong here in my code?
**Re-Edit**
Executed code:
Add-AzureAccount -Environment "AzureCloud"
Set-AzureSubscription -SubscriptionName "My Subs"
$serviceName = "Service01"
$vmName = "Service01"
Get-AzureVM
Error for the above code:
Get-AzureVM : Value cannot be null.
Parameter name: subscriptionId
At D:\TC_PS\Untitled1.ps1:5 char:1
+ Get-AzureVM
+ ~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureVM], ArgumentNullException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.GetAzureVMCommand
You can start from here: Getting Started with Windows Azure PowerShell
Then you can simply run Get-AzureVM that will return all the virtual machines for every cloud service.
To stop a VM: Stop-AzureVM -ServiceName xxx -Name vm-test-01
To stop all the VMs in the subscription simply run: Get-AzureVM | Stop-AzureVM -Force
The -Force switch is necessary to stop the last virtual machine of the cloud service, otherwise the system would throw an error when trying to stop the last VM in the service, to avoid drop all the resources of your published app.
If you don't specify the -StayProvisioned switch, the virtual machine will be deallocated. This is the default behavior of Stop-AzureVM.

What can cause this error: ERROR_DESTINATION_NOT_REACHABLE, Microsoft.Web.Deployment.PowerShell.SyncPackage

Using a Powershell scripted web deploy job, I am receiving this error on some hosts:
C:\> Get-Service msdepsvc,wmsvc
Status Name DisplayName
------ ---- -----------
Running msdepsvc Web Deployment Agent Service
Running wmsvc Web Management Service
C:\> (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\WebManagement\Server' -Name EnableRemoteManagement).EnableRemoteManagement
1
C:\> Add-PSSnapin WDeploySnapin3.0
C:\> $credential = New-Object System.Management.Automation.PSCredential ("some-domain\some-user", (ConvertTo-SecureString "password" -AsPlainText -Force))
C:\> New-WDPublishSettings -ComputerName localhost -Credentials $credential -AllowUntrusted -Site "Default Web Site" -SiteUrl "http://localhost" -AgentType WMSvc -FileName publish.xml
AllowUntrusted : True
PublishUrl : localhost
SiteName : Default Web Site
SiteUrl : http://localhost
Username : some-domain\some-user
Password : password
MySqlDBConnectionString :
SqlDBConnectionString :
AgentType : WMSvc
UseNTLM : False
OtherAttributes : {}
C:\> Restore-WDPackage "package.zip" -DestinationPublishSettings publish.xml
Restore-WDPackage : Could not connect to the remote computer ("localhost"). On the remote computer, make sure that Web
Deploy is installed and that the required process ("Web Management Service") is started. Learn more at:
http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_DESTINATION_NOT_REACHABLE.
At line:1 char:1
+ Restore-WDPackage "package.zip" -DestinationPublishSett ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Restore-WDPackage], DeploymentDetailedException
+ FullyQualifiedErrorId : ERROR_DESTINATION_NOT_REACHABLE,Microsoft.Web.Deployment.PowerShell.SyncPackage
The Windows firewall is not running and the same script runs successfully on other machines (the package is successfully deployed, the website works as expected). As shown above, msdepsvc and wmsvc are both running and wmsvc is configured to allow remote connections. The same machine that fails to accept the Restore-WDPackage command, does accept remote management connections from the IIS management console (after running Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\WebManagement\Server' -Name EnableRemoteManagement -Value 1 and restarting the service). The MS help link contains no clues and the documentation for WDeploySnapin3.0 is not really complete. Other WinRM commands work fine (we create the target website with this script).
What else could be causing the error?