Can't use Get-Service –ComputerName on remote computer - windows

I have a windows 2003 box setup with virtual box and I can't powershell to work with it.
I try this on my windows 7 machine
Get-Service –ComputerName myserver
I get back
Get-Service : Cannot open Service Control Manager on computer 'myserver'. This operation might require other privileges.
At Script1.ps1:2 char:4
+ gsv <<<< -cn myserver
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
While searching around I found I should try and use Enable-PSRemoting.
I did this and now when I try to use it I get
WinRM already is set up to receive requests on this machine. WinRM
already is set up for remote management on this machine.
Yet I still get the same error. Is this because I am using a virtual machine? I setup the virtual OS to be on my domain and I can even use my AD account credentials to log in.
I can get other information back from it.
So it is not like I can't connect to it with powershell.

With PowerShell V2 you've got two approachs for remote commands.
Commands with built-in remoting :
A small set of commands in PowerShell v2 have a -ComputerName parameter, which allows you to specify the target machine to access.
Get-Process
Get-Service
Set-Service
Clear-EventLog
Get-Counter
Get-EventLog
Show-EventLog
Limit-EventLog
New-EventLog
Remove-EventLog
Write-EventLog
Restart-Computer
Stop-Computer
Get-HotFix
These commands do their own remoting either because the underlying infrastructure already supports remoting or they address scenarios that are of particular importance to system management. They are built on the top of DCOM and, on the access point of view, you can use them when you can establish a session with the remote machine with commands like NET.exe or PSExec.exe.
You are trying to use one of them and you've got a problem with credentials (-cred parameter), because your token credentials can't be used to establish an admin session to the remote machine.
The PowerShell remoting subsystem :
Before you can use PowerShell remoting to access a remote computer, the remoting service on that computer has to be explicitly enabled. You do so using the Enable-PSRemoting cmdlet. If you are working in workgroup you also need to enable the server to enter on your client computer with this command (on your client computer as administrator):
Set-Item WSMan:\localhost\Client\TrustedHosts *
Then, you will use New-PSSession Cmdlet (with -computername and -credentials) to create a session object. Then Invoke-Command (with -session and -scriptblock) cmdlet allows you to remotely invoke a scriptblock on another computer. This is the base element for most of the features in remoting. You can also use Enter-PSSession to establish an interactive (SSL like) PowerShell command line with the server.
Useful link : Layman’s guide to PowerShell 2.0 remoting
Test this :
$sess = New-PSSession -ComputerName myServer-Credential (Get-Credential)
Invoke-Command -Session $sess -ScriptBlock {get-service}
...
Remove-PSSession -Session $sess

If it is still important, here is my workaround:
I got an unprivileged user called 'usser' who wants powershell(v2) remoting from client A to server B.
Steps:
enable-psremoting on Targetserver B as admin
Set-PSSessionConfiguration -Name Microsoft.PowerShell -ShowSecurityDescriptorUI on Targetserver B as admin
Add "usser" with full privileges
Now comes the exciting part:
sc sdshow scmanager on Targetserver B as admin
Copy the SDDL output
sc sdset scmanager (f.e.:)"D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)" , in the Output you have to fill after this part (A;;CCLCRPWPRC;;;SY) this = (A;;KA;;;SID)
SID stands of course for the SID of the unprivileged "usser"-user
when everything should be fine, it will similiar looks like this :
D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;S-1-5-21-4233383628-1788409597-1873130553-1161)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)
Hope you will enjoy that little but complicated workaround.

Viewing and manipulating services requires administrative privileges on the target machine.
I was able to duplicate your error message by attempting to run Get-Service -ComputerName MyServer while logged in as a user account that doesn't have administrative rights to the server in question.
You can resolve this by either granting the workstation user account administrative privileges on the target server or by creating a a local group on the server and granting invocation privileges to members of that group. If you want to do the latter, see the following article.
msgoodies: Using a PS Session without having Administrative Permissions

Building on #scusi marcus's brilliant answer here:
Let's say I have an unprivileged/limited user called 'user1' who wants powershell(v2+) remoting from client machine A to targetserver B.
Steps:
From elevated powershell prompt on targetserver B, run enable-psremoting. Accept several Y/N dialog confirmations or else run with -force switch.
In same elevated prompt as step 1, Set-PSSessionConfiguration -Name Microsoft.PowerShell -ShowSecurityDescriptorUI
In the resulting dialog, add "user1". Read privileges should be sufficient unless you are planning on remotely manipulating services, in which case you will want Full Control.
On targetserver B, from an elevated (non-powershell) prompt or as an administrator, run sc sdshow scmanager. Copy the SDDL output. May look something like this: D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)
UPDATE: If we add the limited user to the target computer's Remote Management Users group, we can add (A;;LCRPWPDTLO;;;RM) to the D: portion of the above SDDL string, and skip steps 5 and 6 below.
Determine the SID of the underprivileged user account (in our case, "user1"). (Hint: try wmic useraccount where name='user1' get sid)
Insert the following text into the output we copied in step 5: (A;;KA;;;*SID*) where *SID* is the SID of the user determined in step 5. Insert it somewhere in a place before the S: part of the SDDL string retrieved in step 4. So now you should have a string looking something like this: D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;S-1-5-21-4233383628-1788409597-1873130553-1161)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)
On targetserver B, run sc sdset scmanager followed by our new modified SDDL string. So the entire command would look something like this:
sc sdset scmanager D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;S-1-5-21-4233383628-1788409597-1873130553-1161)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)
You should now be able to remotely access the Service Control Manager on the remote server while logged into client machine A as "user1".
On client machine A, you may find that when you run Get-Service –ComputerName remoteserver not all services are listed. You may need to repeat the above process (starting at step 4) for a specific service that you need remote access to, but which is not listed in your Get-Service output on client machine A. For instance, if the sqlserveragent service is not listed (but you know it is present on the targetserver), you would again log in to targetserver B and execute sc sdshow but this time not for scmanager but for the sqlserveragent service, so sc sdshow sqlserveragent. You would again receive some SDDL output that would need to be manipulated as above. At this point, it may be worth learning more about SDDL (Google it - this link was helpful for me), with the main caveat to watch for the D: and S: portions of the SDDL string and make sure you aren't messing with the S: part.

I know that this isn't the ideal answer to this question, but I was having a similar issue trying to use PowerShell to talk to a Windows 7 box. Turns out, WMI hadn't been installed with the native PSv2 that comes with Win7.
As soon as I installed v3 as part of the WMI 3.0 package, the problem solved itself. I'd suggest making sure that all the relevant WMI services are running on your server. Unless you have conflicts, I'd also recommend upgrading to WMI 3.0.

Related

Install RSAT using powershell script to windows 10 with elevated privileges

I am facing a difficulty on installing RSAT to remote windows 10 workstations via gpo. My main goal is to use Get-ADuser command as a necessity to gain information from my Windows domain.
I created a PowerShell script using the following command:
Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –Online
Yet when I run it, a message appears asking for elevated privileges.
So I tried to add credentials in order to automate the installation and changed the script to :
$Username = 'domain\domain_adm'
$Password = '*******'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Start-Process -FilePath powershell.exe -ArgumentList{Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –Online} -credential $Cred
And from a normal PowerShell window, it works. But, it doesn't when I am trying to use it from gpo.
Could you please assist me?
The goal is to install via GPO Get-ADuser (maybe RSAT) to domain workstations with OS Windows 10
For a small number of machines Powershell is not a bad option. If you have access to GPOs then you should use then. RSAT is "Windows feature". You can use WSUS. https://4sysops.com/archives/install-rsat-1809-and-other-optional-features-in-wsus-environments/ You could also use the software that you use to install software on the machine on the network . Many of software distribution packages run as root when it installs software. In this case just give that team the line below.
Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –Online
Why are you putting credentials in clear text in a script file? That
is just bad practice and should not be done.
Installing software is an Admin level thing, local, GPO, or
otherwise, because it's a system-wide change.
Lastly, this is not a PowerShell code/programming issue and not something PowerShell can fix relative to how you are trying to do this. It's specifically how do I use GPO to enable a Windows feature or install software, using PowerShell?
So, could be considered off-topic for Stackoverflow and more a question for SuperUser or StackExchange.
All that being said, you can still use PowerShell to do this, but doing so by using PowerShell to set a scheduled task to the targets and set that to the admin creds at run once at login.
You can write a separate script to create the scheduled task.
You can use the below script for the RSAT install effort via the task.
Use PowerShell to Create Scheduled Tasks
New-ScheduledTask
Very similar to this approach with updating PowerShell help:
PowerShell: Update-Help via Scheduled Task in Group Policy Preferences
As far as what js2010 has stated. That was true for earlier versions of Windows 10. The current state of things is as noted below.
Install RSAT for Windows 10 1809 and 1903 and 1909 automated
RSAT (Remote Server Administration Tools) in Windows 10 v1809 and
v1903 are no longer a downloadable add-on to Windows. Instead, its
included as a set of "Features on Demand" directly in Windows.
Download: Install-RSATv1809v1903v1909.ps1
Long term Scheduled Task management can be accomplished via GPO as well, as noted here:
Managing Scheduled Tasks from Group Policy
You can download RSAT as an msu file: https://www.microsoft.com/en-us/download/details.aspx?id=45520
EDIT: Ok, as for 1809 and above, my first thoughts are a gpo startup script, or using invoke-command.

How to create windows service to run a powershell script?

I have infinite loop PowerShell (Testing purpose) script, which I want to run as a Service in Windows Server 2008 R2 (Standard).
I'm using the following command to create the Windows service,
sc.exe create "My PS1Service" binPath= "powershell.exe -NoLogo -Path D:\TEST\test.ps1"
And the result is [SC] CreateService SUCCESS
But when I try to run the service My PS1Service , it return the following error
Windows Could not srart the My PS1Service service on Local
Computer
Error 1053: The service did not respond to the start or control
request in a family
Any help here !!!
Due to the length of the articles I don't want to paste them in the answer.
Check out this post which is the most comprehensive source of info I've found regarding powershell services: https://msdn.microsoft.com/en-us/magazine/mt703436.aspx
which links to an example powershell service:
http://jf.larvoire.free.fr/progs/PSService.ps1
I didn't end up successfully modifying this as it was going to take me longer to read through it and understand it than it would to use a different method for my use case, but I'd certainly be going back to that if I needed to create a service in powershell in the future.
Also this: https://www.sapien.com/blog/2017/07/12/write-a-windows-service-in-powershell/
I've been looking all over the place for a decent way to make a PS1 into a service.
Easiest way I found is with Winsw:
https://github.com/kohsuke/winsw
Works like a charm.
I have had success with Non-sucking Service Manager (NSSM) as well. https://nssm.cc/
you can create by below step:
First go to the path where PowerShell script located.
Then run below Command:
powershell.exe -ExecutionPolicy UnRestricted -File .\filename.ps1

Should active directory module for powershell installed on a windows 7 machine to import it or can it be remotely imported from a Windows 2008 R2 DC?

Currently i am working on taskpads for delegating some permissions to remote admins.I have following questions;
-> For Importing active directory module in powershell , shopuld it be locally installed or can it be imported remotely from a windows 2008 R2 DC?
-> For taskpads to work on remote workstations, should the administrative tools be installed on all the remote machines or is there a centralized way of maintaining them?
Please do let me know if anymore clarifications/questions regarding my efforts.
You can import remote module in this way (remoting must be enabled on remote server):
Create a Powershell remote session to a server with the activedirectory module installed.
$Session = New-PSsession -Computername Server1
Use the newly created remote Powershell session to import the module to that session
Invoke-Command -Command {Import-Module ActiveDirectory} -Session $Session
Use that session with the modules to add the available commandlets from the activedirectory module to your local Powershell session adding a name prefix.
Import-PSSession -Session $Session -Module ActiveDirectory -Prefix RM
The code above enables the use of Active Directory commandlets on a computer that doesn’t have this module installed.
Use AD commandlets in the Powershell command shell with modified names based on the -Prefix set above:
Get-RMAdUser instead of the standard Get-ADUser
Get-RMAdComputer instead of the standard Get-ADComputer
You can avoid the -Prefix RM but it's handy for remember that are imported from remote.
For taskpad I'm pretty sure that must be present on each client installing RSAT with the ADUC mmc snap-in.

How do I set the http proxy in a subshell launched from a windows service

I am writing a windows service which takes an uploaded file, runs signtool.exe on it to do the signing and timestamping and then serves the signed file back.
The code for this works when run as a standalone server using twisted however if I try and run it as a service it fails with the error "Signing succeeded, but an error occurred while attempting to timestamp".
If I replace the signcode subprocess call with a curl.exe call which explicitly uses the proxy then this succeeds.
I have set the proxy in internet explorer and running the command manually works. Is there another way of setting an http proxy for signtool/signcode or another way of doing this (I am keen for it to be a service for ease of integration in to some other monitoring systems)?
I have the same issue but running signtool via cygwin ssh (using a password). The timestamping only works via the proxy and over ssh if I login at least once through the gui (e.g. via rdesktop). I don't even have to be logged in to the gui after that for it to work via ssh, I just have to make sure I login at least once via the gui. Whatever it's doing upon graphical login survives a reboot too. One difference however is that I'm setting the proxy settings dynamically using the same powershell that I'm launching via ssh :
$reg_key = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-ItemProperty -path $reg_key ProxyServer -value 192.168.0.3:8888
Set-ItemProperty -path $reg_key ProxyOverride -value "<local>"
Set-ItemProperty -path $reg_key ProxyEnable -value 1
I tried launching explorer.exe &, notepad &, and iexplorer.exe & from ssh but it didn't help. I'll see about hard coding the proxy settings and also if its possible to have the signing user be logged into the gui after boot. Also will check to make sure ssh is launched with cygrunsrv -i or that it's allowed to interact with the desktop is checked in services.
The system reverts its image if it's halted (vmware delta image) (that's how I'm able to duplicate the problem), but I can always change it, which it looks like I might have to do to figure out this problem.
Finally figured it out with some help from the comment here :
http://blogs.msdn.com/b/askie/archive/2013/05/09/user-proxy-settings-showing-up-in-local-system-account-correct-way-to-apply-proxy-settings.aspx#10606266
Looks like the setting actually has to be set in the binary file :
HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections\DefaultConnectionSettings
This binary file doesn't get created in the registry until after graphical login even with the powershell settings I made above. Easiest way is to login (assuming you have the registry settings I made with powershell above, or set it manually through the internet options ui in the gui), export the HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections path, and the import it with :
regedit /s path_to_proxy_settings.reg
If you want it to apply for all users you need to apply the same file under:
HKEY_LOCAL_MACHINE\\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections
as mentioned in the post. There may be other ways as mentioned here https://serverfault.com/questions/34940/how-do-i-configure-proxy-settings-for-local-system , but the above was the easiest for me.

How to uninstall a Windows Service when there is no executable for it left on the system?

How do I uninstall a Windows Service when there is no executable for it left on the system? I can not run installutil -u since there is not executable left on the system. I can still see an entry for the service in the Services console.
The reason for this state is probably because of a problem in the msi package that does not remove the service correctly, but how do I fix it once the service is in this state?
You should be able to uninstall it using sc.exe (I think it is included in the Windows Resource Kit) by running the following in an "administrator" command prompt:
sc.exe delete <service name>
where <service name> is the name of the service itself as you see it in the service management console, not of the exe.
You can find sc.exe in the System folder and it needs Administrative privileges to run. More information in this Microsoft KB article.
Alternatively, you can directly call the DeleteService() api. That way is a little more complex, since you need to get a handle to the service control manager via OpenSCManager() and so on, but on the other hand it gives you more control over what is happening.
Remove Windows Service via Registry
Its very easy to remove a service from registry if you know the right path. Here is how I did that:
Run Regedit or Regedt32
Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"
Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).
Delete Windows Service via Command Window
Alternatively, you can also use command prompt and delete a service using following command:
sc delete
You can also create service by using following command
sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"
Note: You may have to reboot the system to get the list updated in service manager.
Here is the powershell script to delete a service foo
$foo= Get-WmiObject -Class Win32_Service -Filter "Name='foo'"
$foo.delete()
found here
I just tried on windows XP, it worked
local computer:
sc \\. delete [service-name]
Deleting services in Windows Server 2003
We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.
To delete a service:
Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.
Enter command:
sc servername delete servicename
For instance, sc \\dc delete myservice
(Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)
Below is the official help of all sc functions:
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
USAGE:
sc
My favourite way of doing this is to use Sysinternals Autoruns application. Just select the service and press delete.
I'd use PowerShell for this
Remove-Service -Name "TestService"
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-service
Create a copy of executables of same service and paste it on the same path of the existing service and then uninstall.

Resources