find service account on remote hosts - powershell

Could you please advise how to find all servers where a specific service account is being used to start Windows services?
I am trying this in PowerShell with these code:
Clear-Host
$address = Get-Content '.\asg connections.csv'
$serviceName = "startname='NT AUTHORITY\\LocalService'"
gwmi Win32_Service -Filter $serviceName -Computer $address
Above piece of code works for "localhost", but gives below error for the remote hosts:
gwmi : Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED))
At F:\Temp\powershell\play.ps1:30 char:1
+ gwmi win32_service -filter $serviceName -computer $address
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

When you use PowerShell remoting you implicitly trying to use the credentials your current Windows session is logged into your machine with on the target machines.
It looks like you do not have any rights with your current set of credentials on those machines.
Are the target machines joined into the same domain as your current user credentials?
If you have a set of working credentials you can log onto those machines with, you can add it in your command with:
Clear-Host
#Promts you for the username and password you wish to save to a credential object
$Cred = Get-Credential
$address = Get-Content '.\asg connections.csv'
$serviceName = "startname='NT AUTHORITY\\LocalService'"
gwmi Win32_Service -Filter $serviceName -Computer $address -Credential $Cred
If the script needs to run automated there are a few different ways to save credential passwords either into an encrypted textfile that can only be decrypted by the user account that encrypted it, or using the build in Windows Credential Vault.

Related

Script creates local admin and then adds it to service with different password

I have a script that creates a local user account, sets the password, adds the local account to Administrators group, and then sets a service to run as this account. The problem is when trying to restart the service I get an error:
Error 1069: The service did not start due to a logon failure.
I found out that when I manually set the password, I'm able to start the service.
The problem seems to be how the password is passed to the $service.Change($null,...,$password,...,$null) method.
$name = $env:COMPUTERNAME
$computer=[ADSI]"WinNT://$name"
$newuser = $computer.Create('User','newuser')
$password = "Password1"
$newuser.SetPassword($password) #this works
$newuser.SetInfo()
$admin = "Administrators"
$group=[ADSI]"WinNT://$name/$admin,Group"
$group.Add($newuser.path)
$service = Get-WmiObject Win32_service -filter "name='ServiceName'"
$service.Change($null,$null,$null,$null,$null,$null,".\newuser",$password,$null,$null,$null) #this doesn't. Password has not changed.
Restart-Service -Name $service.Name
Restart-Service : Service 'Service Name (ServiceName)' cannot be started due to
the following error: Cannot start service ServiceName on computer '.'.
At C:\Users\superfoo\Documents\Scripts\ServiceUpdate.ps1:68 char:3
+ Restart-Service -Name $serviceControl
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Restart-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.RestartServiceCommand
The $password works while creating the account but not for setting the password on the service. I am running the script as administrator.
OS: Windows 10 (x64)
Powershell: Version 5.0.10586.122

Powershell Invoke-Command Operations Error

I'm stumped by this issue.
I've written a powershell script which I'm trying to use to import a GPO across multiple domains and then link it with new-gplink. I've made sure all servers have GP Powershell module installed and it's been working pretty well so far, however the issue I'm running into is that on some servers my command works fine on others I get the error, on the last step I'm getting an operations error one of my invoke-commands. Other commands work on the same server with invoke-command such as get-service, or even the import-GPO command that I use.
The error in question:
An operations error occurred. (Exception from HRESULT: 0x80072020)
+ CategoryInfo : NotSpecified: (:) [New-GPLink], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.GroupPolicy.Commands.NewGPLinkCommand
+ PSComputerName : 10.0.0.10
The command:
Invoke-Command -ComputerName $serverip -scriptblock {New-GPLink -Name "GPO" -Target $args[0]} -ArgumentList $oupath -credential $cred
I've tried every version of this command I can imagine. without [0], without argument list, just using the server ip and replacing the target with the OU path and I still get the same error, such as below.
Invoke-Command -ComputerName $serverip -scriptblock {New-GPLink -Name "GPOName" -Target ou=users,ou=site,ou=domain,dc=server,dc=com} -ArgumentList $oupath -credential $cred
The way I have it working is a .csv with the server info, it gets imported into a foreach loop and then fed into the script. I have it grab credentials and feed through. I know everything else is working because my invoke-command to import the GPO worked, all servers I ran to successfully imported the GPO. I also know my OU paths are correct because I use them locally with another script to place computers where I want them. a sample line in the csv would be something like
servername, 10.0.0.10, domain.com, OU=user,OU=site,DC=domain,DC=com
I've also ran the command locally and get a similar error:
PS> New-GPLink -Name "GPO" -Target "ou=users,ou=Site,dc=domain,dc=com"
New-GPLink : A referral was returned from the server.
At line:1 char:1
+ New-GPLink -Name "GPO" -Target "ou=users,ou=site,dc=domain,d ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-GPLink], DirectoryServicesCOMException
+ FullyQualifiedErrorId : System.DirectoryServices.DirectoryServicesCOMException,Microsoft.GroupPolicy.Commands.NewGPLinkCommand
Please let me know if there are additional question or if you need additional info. I'm completely stumped by this issue and I appreciate any help you can provide. Thanks in advance.
Edit: All of my servers are at least 2008 R2 and are using powershell version 3,0,1,1
PS> $psversiontable.psversion
Major Minor Build Revision
----- ----- ----- --------
3 0 -1 -1
You need to specify a the domain in which your trying to apply the GPO, as well as a Domain Controller from the domain in question with the -Domain and -Server parameters respectively:
$OU = "ou=users,ou=Site,dc=domain,dc=com"
New-GPLink -Name "GPO" -Target $OU -Server "domain.com" -Domain "domain.com"
Instead of just using the domain name though, the proper way to do this, is to actually locate a Domain Controller, like so:
$DC = Get-ADDomainController -Discover -DomainName "domain.com" |Select -ExpandProperty HostName
New-GPLink -Name "GPO" -Target $OU -Server $DC -Domain "domain.tld"
Or in an environment where Get-ADDomainController is not available, you can emulate the DCLocator (aka. the underlying high-availability design of AD DS) behavior with .NET:
$DomainFqdn = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$dctx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext -ArgumentList "Domain",$DomainFqdn
$DomainController = $[System.DirectoryServices.ActiveDirectory.DomainController]::FindOne($dctx)
New-GPLink -Name "GPO" -Target $OU -Server $DomainController.Name -Domain $DomainFqdn

vSphere Powercli - The specified privileges are from a different server

I have the following powercli script to add a local account to an esx host.
With all my research I believe this should work but when I run it I get this error.
New-VIRole : 3/04/2014 9:23:49 a.m. New-VIRole The specified privileges are from a different server.
At .\test.ps1:18 char:11
+ New-VIRole <<<< -Name "CIM Only" -Privilege "CIM interaction"
+ CategoryInfo : InvalidArgument: (VMware.VimAutom...ent.Privilege[]:Privilege[]) [New-VIRole], VimException
+ FullyQualifiedErrorId : Core_NewVIRole_DoWork_PrivilegeFromDifferentServerSpecified,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.NewVIRole`
Here is the script
## As usual, load needed PowerCLI cmdlets
asnp VMware.VimAutomation.Core -ErrorAction SilentlyContinue
# Define the ESXi server
$server = "servername"
#Connect to ESXi server
Connect-VIServer -Server $server -user user -password password
#Create a new role CIM, with the only needed privilege assigned to it
New-VIRole -Name "CIM Only" -Privilege "CIM interaction"
#Create the cimuser account, assign it to root group, and deny it shell access
New-VMHostAccount -Id cimuser -Password password -UserAccount:$true -AssignGroups root -GrantShellAccess:$false
#Assign the role CIM to the newly created cimuser account
New-VIPermission -Entity $server -Principal cimuser -Role "CIM Only"
#Disconnect from ESXi server
Disconnect-VIServer -Server $server -Confirm:$false
Any help greatly appreciated.
Try this:
New-VIRole -Name "CIM Only" -Privilege ( Get-VIPrivilege "CIM interaction" )
What esxi version are you running?

Nagios Issue - gwmi : The RPC server is unavailable

I'm struggling with a problem regarding the RPC server being unavailable specifically for a Nagios script written in PowerShell.
When the script is run locally, it runs perfectly and as expected. When it is called via the NRPE agent and run by the nscp service, it fails with this error:
gwmi : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\Program Files\NSClient++\scripts\check_win_uptime.ps1:30 char:8
+ $wmi = gwmi Win32_OperatingSystem -computer $ServerName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands
.GetWmiObjectCommand
The guts of the script (or relevant parts) are this:
$wmi = gwmi Win32_OperatingSystem -computer $ServerName
$LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)
[TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)
No firewall is running and for testing purposes, all ports are open to the server.
Any suggestions are greatly appreciated.
Mike
RPC Server Unavailable is almost always not having enabled the right settings in Windows firewall. See this very old topic I got written for MSDN while on the WMI team to document the issue.
Connecting thru Windows Firewall
Get-wmiobject -computer is very finicky. This works for me:
$c = get-credential
Get-WmiObject -Class win32_computersystem -ComputerName comp001 -Credential $c
But other forms give the "Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)" error:
Get-WmiObject win32_computersystem -ComputerName comp001 -Credential $c
Get-WmiObject -Class win32_computersystem -ComputerName comp001 # running as same domain user as creds
So it looks like -Class and -Credential are mandatory.
Sometimes only something like this works:
Get-WmiObject -ComputerName comp001 -Credential "dom\js" -Query "SELECT * FROM Win32_ComputerSystem"
I have encountered the problem alike but via CMD using tasklist to view remote processes. The answer is related to firework config. Convert this to a PowerShell command and it will solve your problem.
netsh advfirework firework set rule group="windows management instrumentation (wmi)" new enable=yes

Get-WmiObject credentials not working when scheduled

I have a Powershell script to detect disk space on a network server that requires a user/password to access it.
I followed this: http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/440ab7ed-7727-4ff7-a34a-6e69e2dff251/
To get this code:
$password = get-content C:\creds.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "username",$password
Get-WmiObject -ErrorAction Stop Win32_LogicalDisk -ComputerName $deviceName -credential $cred -Filter "DeviceID='$darg'"
$deviceName and $darg are already correctly defined.
This works just fine when running the Powershell script manually. But when I set it up as a Windows schedule task, it fails thinking the user/pass is incorrect:
Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESS
DENIED))
$disks = Get-WmiObject <<<< -ErrorAction Stop Win32_LogicalDisk -ComputerName $deviceName -credential $cred -Filter
"DeviceID='$darg'"
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], Unauthorized AccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Why is this? (The account is a local user on the remote server. I've tried entering the credentials on the Schedule interface but it doesn't let me save it, saying invalid login; maybe due to being a local account) ServerName\LocalUser does not work in the Windows Schedule UI, still gives the incorrect login error.
Here is my comment, re-worded as an answer.
The convertto/from-securestring functions work on a per-user basis (if you don't provide a specific key value). IOW, one user can't read another user's data.
This pre-existing SO question seems relevant. There is also relevant discussion at Powershellcommunity.org.
why dont you set the task to run under the user account and run the wmi request without credential ?