Get Service from remote machines in a domain - powershell

Trying to get list of all machines in a Domain with a certain service
tried via all posts in here, helped per one machine, but if i use a text file with multiple machines, it failes
$computers = Get-Content c:\script\computers.txt
$service = "*crystal*"
foreach ($computer in $computers) {
$servicestatus = Get-Service -ComputerName $computer -Name $service
}
$Data = $servicestatus | Select-Object Name,Machinename | Format-Table -AutoSize
Write($Data) | Out-File c:\script\output.txt -Append
Expected list of machines with service in table, instead got error:
This operation might require other privileges
same script, but with a direct machine name, works like a charm.
Any clue what is wrong?

Why not use:
Invoke-Command -ComputerName $computers -ScriptBlock {Get-Service -Name *crystal*}
Eventually you may store the result from invoke into a variable and work with it.
The benefit of using Invoke-Command, insted of foreach is that Invoke works in parallel, while foreach is serial ...
Hope it helps!
Best regards,
Ivan

Related

How do i get power shell to show a few services from my servers and not them all

this is my code i want it to show a few services from my servers but it keeps showing all of them. i tried using -Name but power shell 7 keeps saying that doesn't exist please help
$offlineServices = (Invoke-Command -ComputerName $server.Name {Get-service [string]$server.Value | `
Where-Object{$_.status -eq 'Stopped'}} ).Name
Get-Service can be used directly against remote servers, like this:
Get-Service -Name $server.Value -ComputerName $server.Name |
Where-Object Status -eq 'Stopped'
If you want to stick with your original remoting technique, you need to use the using modifier:
$offlineServices = (Invoke-Command -ComputerName $server.Name -Script {Get-service $using:server.Value |
Where-Object Status -eq 'Stopped'}).Name
NOTE: you should also remove the backtick before Where-Object as it isn't needed and might cause you issue later when modifying/debugging the code.

Powershell to query specific Service in enterprise?

Good day good people.
Would someone please help me out I am trying to PS our enterprise servers to find all assets with a particular service on it and having no luck.
I tried
$servicename = "SERVICE_NAME"
$list = get-content "c:\security\comp_list.txt"
foreach ($server in $list) {
if (Get-Service $servicename -computername $server -ErrorAction 'SilentlyContinue'){
Write-Host "$servicename exists on $server
}
Any suggestions would be greatly appreciated. I'm still fairly new to PS.
My accepted answer to why Get-Service -ComputerName fails can be found in the link below and the resolution to the issue.
Powershell Results to Slack via Webhook question - Remote Server results
Summary
Differences between Windows PowerShell 5.1 and PowerShell 7.x
Please Note In Windows 7.2 the Get-Service command made use of DCOM and such functionality like '-ComputerName' is removed.
https://learn.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7#remove--computername-from--service-cmdlets-5090
$server = $env:Computername
Invoke-Command -Computername $server -Scriptblock {Get-Service | where status -eq 'started;}
Get-Service cmdlet
The cmdlet gets the members, the properties and methods, of objects
get-service | get-member | sort Name
Names of services that start / contain 'App'
$Results = Get-Service -Name App | Select Name

Remote command output to text file (remote system)

I know I must be using these commands wrong but I can't seem to find a solution. I believe the issue is with my use of the invoke-command and out-file. I'm trying to check to see if a process is running on multiple remote machines and write their states back to a text file on the host system. Even if it wrote to the remote system I could work with that but I cant seem to get anything.
$MyDomain=’mydomain’
$MyClearTextUsername=’myusername’
$MyClearTextPassword=’mypassword’
$MyUsernameDomain=$MyDomain+’\’+$MyClearTextUsername
$SecurePassword=Convertto-SecureString –String $MyClearTextPassword
-AsPlainText –force
$MyCredentials=New-object System.Management.Automation.PSCredential
$MyUsernameDomain,$SecurePassword
$Servers = ( "server1","server2","server3")
$output = foreach ($Server in $Servers)
{
$Session = New-PSSession -ComputerName $Server -Credential $MyCredentials
Invoke-Command -Session $Session -ScriptBlock
{
Get-Service -Name service | select name, status, PSComputername, Runspaceid
} | Out-File -filepath 'c:\TEMP\check.txt'
}
Write-output $output | Out-File -filepath 'c:\TEMP\check.txt'
edit: I don't believe the last line is needed but I threw it in just to see if I could get anything out.
You are not capturing anything in $output because you are redirecting all of the output from your Invoke-Command to Out-File -filepath 'c:\TEMP\check.txt'. Get-Service doesn't return that much data, especially once's it's been deserialized when it returns from the remote session, so I wouldn't bother with the Select statement. Even if you do want to include the Select statement you are specifying PSComputerName which doesn't get added until the data comes back from the remote system, so you may want to move that Select to outside of the scriptblock and after the Invoke-Command in the pipeline. Plus, since you are outputting with Out-File your local file is being overwritten each time that call is made, so the first server's results are saved, then overwritten by the second server's results, then by the third server's results. After that, since $output has nothing (as all output was redirected to file), you are outputting an empty variable to the same file, effectively erasing the service state of the third server.
But this really all becomes a moot point if the script is run with the credentials that has access to the remote servers. You can specify one or more computer names to the Get-Service cmdlet, so this could become as simple as:
$Results = Get-Service Service -ComputerName 'Server1','Server2','Server3'
$Results | Select name, status, PSComputername, Runspaceid | Set-Content 'C:\TEMP\check.txt'
Just to make sure... you are looking for a service right? Not just a process? Because if it isn't a service you would need to use Get-Process instead of Get-Service.
If you want to output the data to the remote server you could do:
$output = foreach ($Server in $Servers)
{
$Session = New-PSSession -ComputerName $Server -Credential $MyCredentials
Invoke-Command -Session $Session -ScriptBlock
{
Get-Service -Name service | Tee-Object -FilePath C:\Temp\ServiceState.txt
} | select name, status, PSComputername, Runspaceid
}
$output | Out-File -filepath 'c:\TEMP\check.txt'
That should make a file in the C:\Temp folder on each server with the state of the service, as well as pass the information back to the local host, where it is passed to Select and stored in $output. At the end I output $output to file, just as you did.
I guess in the end you could just remove the Out-File call from within your loop, and it would probably do what you want it to.

Why am i receiving RPC server is unavailable error when looping?

I have a Powershell script to find specific servers and their corresponding service accounts. If I modify the script to use a single server and a single service account, the results are what I expect. If I loop thru the servers and accounts, I receive the following error:
#################################################################
# Find Service Account(s) used to start Services on a Server(s) #
#################################################################
$accounts = (Get-Content C:\Users\location\Scripts\Service_Accounts.txt)
Remove-Item -path C:\Users\location\Scripts\ServiceAccountFnd.txt -force -erroraction silentlycontinue
Import-Module ActiveDirectory # Imports the Active Directory PowerShell module #
## Retrieves servers in the domain based on the search criteria ##
$servers=Get-ADComputer -Filter {Name -Like "namehere*"} -property *
## For Each Server, find the services running under the user specified in $account ##
ForEach ($server in $servers) {
Write-Host $server
ForEach ($account in $accounts) {
Write-Host $account
Get-WmiObject Win32_Service -ComputerName $server | Where-Object {$_.StartName -like "*$account*"} | Format-Table -HideTableHeaders -property #{n='ServerName';e={$_.__SERVER}}, StartName, Name -AutoSize | Out-File -FilePath C:\Users\location\Scripts\ServiceAccountFnd.txt -append -Width 150
}
}
Your $server variable does not only contain the hostname, but also all attributes of the AD computer object.
Try to change the ComputerName value to $server.name.
If that doesn't help: Can you confirm, that you used the very same computer in the loop as without the loop, as you described? I'd assume that you try to access another computer, which is not configured as expected.
Besided that, I'd recommend you to use Get-CimInstance rather than Get-WmiObject, as it doesn't use RPC, but WinRM by default. WinRM is more firewall friendly, secure and faster.

powershell exchange 2003 : wmi-object does not pull all mailbox stores?

I have the following code pulling from my exchange server 2003.
connect-qadservice -service 'localhost'
foreach ($server in $exchangeservers)
{
$AllUsers += get-wmiobject -class Exchange_Mailbox -namespace Root\MicrosoftExchangeV2 -computername $server| select servername,storagegroupname, storename,mailboxdisplayname,totalitems,size, DeletedMessageSizeExtended, legacyDN, datediscoveredabsentInDS
}
$exchngver = "2003"
foreach ($user in $AllUsers)
{
$obj = new-object psObject
$office = get-qaduser -Identity $user.legacyDN | select office, description
}
disconnect-qadservice
and it doesn't grab all the mailbox stores on the server. Any idea why or what might be causing this?
thanks in advance
NOTE: IT seems to grab all the mailbox stores except for 1 in the 2nd storage group. I have no idea why this is... The funny thing is my vbscript grabs all the mailbox stores using the same namespace and class just fine.
So to start simple, does it come back correct before you unroll & start using the quest stuff?
Do you get the right number from:
(get-wmiobject -class Exchange_Mailbox -namespace Root\MicrosoftExchangeV2 -computername srv02).count
Have you checked permissions on the Stores/SGs?
Couple of things (not sure they are the cause (#1)):
you are looping over $exchangeservers but don't use $server in -computerName (there's a fixed "srv02" server name).
I would move the connect-qadservice -service 'localhost' out of the foreach servers loop (You call it for each server in exchangeservers).
You are calling get-qaduser twice ($tmp and $office) to get the user office and description, you can do it in one call ($tmo is redundant):