Not able to run PowerShell on Jenkins - powershell

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

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

Powershell VSCode invoke-command from localhost different user for SCCM

Because VSCode is not able to run a powershell console and debug it as a different user i am trying to get arround it with invoked credentials like this:
Start-Service -Name "WinRM"
$cred = Get-Credential -Credential domain\myuser
Invoke-command -Credential $cred -Computer "localhost" -scriptblock {
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
Set-Location 'XXX:' # my sccm site code
Import-CMComputerInformation -CollectionName "All Systems" -ComputerName "TestComputer" -MacAddress "00:00:00:00:00:69"
}
If i start it in the debugger of VSCode (F5) it starts but cant connect then to the SCCM Server infrastructure. Could someone help me to solve this issue?
Error:
Cannot find drive. A drive with the name 'XXX' does not exist.
+ CategoryInfo : ObjectNotFound: (XXX:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : localhost
This command cannot be run from the current drive. To run this command you must first connect to a Configuration Manager drive.
+ CategoryInfo : DeviceError: (Microsoft.Confi...ormationCommand:ImportComputerInformationCommand) [Import-CMComputerInformation], InvalidOperationException
+ FullyQualifiedErrorId : CommandCannotExecuteFromCurrentDrive,Microsoft.ConfigurationManagement.Cmdlets.Oob.Commands.ImportComputerInformationCommand
+ PSComputerName : localhost
If i logoff from my machine and login with my admin credentials and execute everything in the invoke-command scriptblock it works.
As i am not allowed to work like this by our company policy's is there maybe a alternative way or something i can do to use the visual studio code debugger?
Have you logged onto the SCCM site server interactively with the credentials you are using and opened the console at least once? I believe this initial first opening is required before the drive is accessible remotely...

PowerShell Stopping and Starting Services with Server names masked by DNS Alias

I have a simple PowerShell that accepts a file as a parameter that contains Server-Name, Service-Name and Timeout specified in seconds and the powershell stops/starts the services based on the command. I have 10 servers where application related services are configured and I'm using Workload automation capabilities to run this code on any server with the same parameter file and powershell present on all 10 servers.
All of this works fine with server names hardcoded in the param file. We have n+2 Infrastructure, and I created DNS Aliases for all the 10 servers to make Active-Standby switchover little easy. Now the problem comes with stop/start script. Ex: If the script gets invoked in Server 7, all the services will be shutdown except for the ones in Server 7 and I get below error:
Get-Service : Cannot find any service with service name
'Application-Server7'. At line:1 char:1
+ Get-Service -ComputerName app7test -Name Application-Server7
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Application-Server7:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
I just tested one-liner command using PowerShell ISE on the computer "appnewora79" and below are the results.
This works fine:
Get-Service -ComputerName appnewora79 -Name Application-Server7
Status Name DisplayName
------ ---- -----------
Stopped Application-Ser... Application-Server7
This fails:
Get-Service -ComputerName app7test -Name Application-Server7
Get-Service : Cannot find any service with service name 'Application-Server7'
At line:1 char:1
+ Get-Service -ComputerName app7test -Name Application-Server7
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Application-Server7:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Any suggestions to overcome this, please?
I tried below as well:
It all works when the server name is hardcoded. If I change it to DNS Alias name then Get-Service fails on the server where it is executing while fetching service details only related to the same server.
On the Server-1, if I run below commands, they all work fine
Get-Service -ComputerName servername1
Get-Service -ComputerName servername2
Get-Service -ComputerName servername3
If I update the above command with server dns alias and execute them on Server-1, then only the first command fails, i.e.. the command with the same server name masked with DNS fails, If I run the same commands on server 2, then the second one alone fails
Get-Service -ComputerName dnsalias1
Get-Service -ComputerName dnsalias2
Get-Service -ComputerName dnsalias3
I tried, test-connection with DNS alias names and they go thru fine. Tried Get-WmiObject -Class WIN32_service with computer name masked as DNS alias and it goes thru fine. I'm lost as to what could be the issue.
Below is the error message with Get-Service alone:
Get-Service : Cannot open Service Control Manager on computer 'dnsalias1'. This operation might require other privileges.
At line:5 char:1
+ Get-Service -ComputerName dnsalias1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
I found a kind of different way to resolve this as per suggestion received in PowerShell Google+ forum.
I used Resolve-DnsName to get hold of IP4Address of the server and then passed it for stopping and starting windows services and this works.

PowerShell remote restart service running from a TFS build error

I have a TFS build definition contains a PowerShell Script build step. I would like to run the following command on a remote computer(DEVWS45PC) which should restart the service named StartSeleniumGridHub:
winrm s winrm/config/client '#{TrustedHosts="DEVWS45PC"}'
Restart-Service -InputObject $(Get-Service -Computer DEVWS45PC -Name StartSeleniumGridHub)
This gives me this error:
##[error]Get-Service : Cannot find any service with service name 'StartSeleniumGridHub'.
At E:\builds_2017\killBrowsersOnAllNodesAndRestartHub.ps1:43
char:36
+ Restart-Service -InputObject $(Get-Service -Computer DEVWS45PC -Name StartSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (StartSeleniumGridHub:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Restart-Service : Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At E:\builds_2017\killBrowsersOnAllNodesAndRestartHub.ps1:43
char:34
+ Restart-Service -InputObject $(Get-Service -Computer DEVWS45PC -Name StartSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Restart-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RestartServiceCommand
I can run this script without any problem from any of my computers. Note that 'DEVWS45PC' is truly set as a trusted host on the TFS build agent computer, so it's not the problem.
I have no clue what is the problem. Maybe authentication problems?
You could manually RDP to the remote machine DEVWS45PC with your build service account and run the powershell script.
Most likely lacking of permissions of your build service account(Due to could not find the service). Suggest you add the service account to your local Administrator group on the remote machine DEVWS45PC and try again.
Also make sure you are using the PowerShell on Target Machines task instead of powershell task in the build definition.

Powershell stop-service error: cannot find any service with service name

I'm working on a script to deploy vendor software to a large environment. The first step is to stop the services in question. The script executes fine in our test environment, but I'm not an admin in the production environment so I'm convinced it's a permissions issue. I can't get admin rights to the prod environment so I need to try to find out anything that I may need to set to grant permissions to stop services remotely. I'm issuing the following command to stop services:
Stop-Service -InputObject $(Get-Service -Computer $destination.Server -Name ("moca."+$destEnv))
When I run the script I get:
Cannot find any service with service name 'moca.WMSPRD'.
+ CategoryInfo : ObjectNotFound: (moca.WMSPRD:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
+ CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StopServiceCommand
The service definitely exists and if I rdp into the target box and issue the stop-service command locally it will execute. So there is something preventing me from stopping the service remotely. Any ideas?
Edit:
A coworker suggested using WMI so tried replacing the Stop-Service line with:
(Get-WmiObject -computer $destination.Server Win32_Service -Filter ("Name='moca."+$destEnv+"'")).InvokeMethod("StopService",$null)
and I get:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
If you know the exact service name you can try this
(Get-WmiObject -computerName $_.name Win32_Service -Filter "Name='moca'").StopService()
Here im assuming that the service name is moca
Is DCOM working on the remote computer? I know how to do it with remote powershell, which uses wsman:
invoke-command comp001 { stop-service adobearmservice }