Command .startservice() not working in Powershell - powershell

I have a little script where the user enters the script name (the description name) and has the option to modify the properties. This is done with a GUI interface: a textbox and some drop-down lists.
I tried several ways to make it but none of them worked.
Here is how I retrieve the service information:
$thisservice = Get-WmiObject -Class Win32_Service -ComputerName $Server | Where { $_.displayName -eq $serviceBox.text }
I look at $server computer and match up the "service display name" to the value contained in the textbox field: $_.displayName -eq $serviceBox.text. This works well, if I list the data I get exactly what is in the service console: .name, .description, .state, .startmode, .displayname
I store the service name in a variable:
$servicename = $thisservice.name
I know you can not start a service unless it is on "Manual" or "auto" so first I set it to auto. Here I tryed to different ways but none worked:
$servicename.ChangeStartMode("Auto")
and
Set-Service $servicename -StartupType Auto
and then I start the service (but this doesn't work either even if I preset the state-mode on Auto form the service manager):
$servicename.startservice()
Also the $servicename.stopservcie() fails.
I tried this on 2 different machines, on both I have admin rights, I tryed running the script with Admin mode, same result. I even tried it directly from PS console and I couldn't change the service state!
What am I doing wrong?

Your problem is here: $servicename = $thisservice.name
By doing that you set $servicename to be a string, not the service object. Therefore you can't call service methods on it any more.
You should be able to just do:
$thisservice.ChangeStartMode("Automatic")
$thisservice.StartService()

Related

PowerShell to stop and disable a service. Reading the servers from a TXT file

I see some questions about this topic, but I cannot get it working
Get-Service -Name Spooler -ComputerName (Get-Content c:\tmp\scripts\Servers\iservers.txt) |
Stop-Service -PassThru | Set-Service -StartupType Disabled -whatif
The code executes for each server on the txt file, and stops de service, but not disable the service.
Any help to get it work and/or Troubleshooting???
Regards.
How to approach this kind of problem
In automation, we work up to complexity, meaning you should start simply and then add on more features until you see where it breaks.
Right now, you're trying to do a bunch of operations in one single line:
Load a list of computers and
Reach out to the computers and Stop a service and
Also while doing this, set the service to not automatically start.
There are a lot of problems you can run into, like "what happens if these PCs aren't enabled for remoting", or "what if you need a different account to handle stopping or disabling a service".
When you're trying to figure it all out in one-line, you're in for a bad and frustrating time.
How to fix it
Start simply. Start with one computer that's nearby and definitely turned on.
Begin with reading a service. Can you even get this operation to run?
Get-Service -ComputerName SomePC123 Spooler
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
If you run into an error, then first figure out how to be able to remote into that one PC and see if the Print Spooler is running. Then, you will know what steps to deploy to all of your machines to prepare them for remoting.
Then, once you can check if a service is running, you can add on the next step, try to stop the service.
So your code would start to look like this:
$computers = get-content .\someTextFile.txt
forEach($computer in $computers){
$service = Get-Service -ComputerName $computer Spooler
"status of spooler on $computer is $($service.Status), with start type of $($service.StartType)"
#todo, set start type to Disabled...
}
Eventually, you will have migrated each step out of the one-liner and you'll know where and why any given command is failing. This is the way.

How to run VMware commands from remote scripts on windows

Have a local basic Powershell form for searching and creating VMware virtual machines.
Using new powershell powerCLI module, as described in link
Let's take Get-VM for example:
LOGIC: Type a certain string in TextBox > click search > prints VM's status/parameters in the form
The problem is, I can't execute Get-VM straight away from the script, but first have to connect using Connect-VIServer command and only than Get-VM will work
Is there any way to do it from the script? Something similar to -m flag of commands plink or putty.
Like: Connect-VIServer -server testvc -flagForExample "commands_list.txt"
Yes, you can. Before providing an immediate answer I'd like to explain what is actually happening.
When you call Connect-VIServer the command sets the value of the variable $DefaultVIServer behind the scenes, which is later used by other cmdlets (such as Get-VM).
However, the Get-VM documentation states that there is a Server parameter available. Which means that you can store your server connection in a variable and then pass it to the Get-VM cmdlet.
Here's a pseudo-code example:
$server = Connect-VIServer -server testvc
Get-VM -Server $server
Furthermore, the Get-VM supports an array of servers, so theoretically you can run the cmdlet on multiple servers at once. For example:
$server1 = Connect-VIServer -server testvc
$server2 = Connect-VIServer -server testvc2
Get-VM -Server #($server1, $server2)

Configure SharePoint 2010 UPS with PowerShell

SOLUTION FOUND: For anyone else that happens to come across this problem, have a look-see at this: http://www.harbar.net/archive/2010/10/30/avoiding-the-default-schema-issue-when-creating-the-user-profile.aspx
TL;DR When you create UPS through CA, it creates a dbo user and schema on the SQL server using the farm account, however when doing it through powershell it creates it with a schema and user named after the farm account, but still tries to manage SQL using the dbo schema, which of course fails terribly.
NOTE: I've only included the parts of my script I believe to be relevant. I can provide other parts as needed.
I'm at my wit's end on this one. Everything seems to work fine, except the UPS Synchronization service is stuck on "Starting", and I've left it over 12 hours.
It works fine when it's set up through the GUI, but I'm trying to automate every step possible. While automating I'm trying to include every option available from the GUI so that it's present if it ever needs to be changed.
Here's what I have so far:
$domain = "DOMAIN"
$fqdn = "fully.qualified.domain.name"
$admin_pass = "password"
New-SPManagedPath "personal" -WebApplication "http://portal.$($fqdn):9000/"
$upsPool = New-SPServiceApplicationPool -Name "SharePoint - UPS" -Account "$domain\spsvc"
$upsApp = New-SPProfileServiceApplication -Name "UPS" -ApplicationPool $upsPool -MySiteLocation "http://portal.$($fqdn):9000/" -MySiteManagedPath "personal" -ProfileDBName "UPS_ProfileDB" -ProfileSyncDBName "UPS_SyncDB" -SocialDBName "UPS_SocialDB" -SiteNamingConflictResolution "None"
New-SPProfileServiceApplicationProxy -ServiceApplication $upsApp -Name "UPS Proxy" -DefaultProxyGroup
$upsServ = Get-SPServiceInstance | Where-Object {$_.TypeName -eq "User Profile Service"}
Start-SPServiceInstance $upsServ.Id
$upsSync = Get-SPServiceInstance | Where-Object {$_.TypeName -eq "User Profile Synchronization Service"}
$upsApp.SetSynchronizationMachine("Portal", $upsSync.Id, "$domain\spfarm", $admin_pass)
$upsApp.Update()
Start-SPServiceInstance $upsSync.Id
I've tried running each line one at a time by just copying it directly into the shell window after defining the variables, and none of them give an error, but there has to be something the CA GUI does that I'm missing.
For anyone else that happens to come across this problem, have a look-see at this: http://www.harbar.net/archive/2010/10/30/avoiding-the-default-schema-issue-when-creating-the-user-profile.aspx
TL;DR When you create UPS through CA, it creates a dbo user and schema on the SQL server using the farm account, however when doing it through powershell it creates it with a schema and user named after the farm account, but still tries to manage SQL using the dbo schema, which of course fails terribly.
The workaround is to put my code into its own script file, and then use Start-Process to run the script as the farm account (it's a lot cleaner than the Job method described in the linked article):
$credential = Get-Credential ("$domain\spfarm", $SecureString)
Start-Process -FilePath powershell.exe -ArgumentList "-File C:\upsSync.ps1" -Credential $credential

Why would Get-Service not find the service with powershell

I am having problems with a powershell script.
I wrote a script that would search for a windows service with a specific name, and it would Stop or Start this service.
It works when I run it on a server which I log into with a service account that I know that can access the service console. However when it runs off of my build server, the script is no longer able to find the services. I tried giving the service account that runs script the same privaledges as the other service account but that doesn't seem to work.
[System.ServiceProcess.ServiceController]$service = Get-Service -Name $ServiceName -ComputerName $Remoteserver -ErrorAction SilentlyContinue
That is the line that is not longer able to find the service. What am I doing wrong. Is there a way to impersonate a user that can find the service? Any help would be appreciated.
You could try supplying the credentials of the service account using the -Credential parameter. However, since you imply that it used to work with the account that runs the script remotely and no longer does, I think a more likely culprit is that $ServiceName used to only match one service on the target computer, and now there is another service whose name matches that string. If more than one service matches the -Name parameter, Get-Service returns an array of ServiceController objects.
Try running it without ErrorAction -SilentlyContinue. If you get the following error message, then that's what's happening:
Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.ServiceProcess.ServiceController".
If you get a different error message, please add the full error message to the question.

Configure service with Set-Service

Can I set a service to run in its own container thru Powershell? ie.
What is the Powershell equivalent of sc config <service name> type= own
You can change service type property on the corresponding WMI object.
# get service
$s = (Get-WmiObject win32_service -filter "Name='Fax'")
# change service type
$s.Change($null, $null, 16) # 16 = "Own Process"
Other values you can find here (http://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx)
Make sure that ReturnValue from change method is equal to 0. Meaning of error codes you can find in the link above.