1

How can i add the server name at the left of each line result on this script?. Thank you!

$servers = Get-Content -path .\Machines.txt
[pscustomobject]$result = @()  
$subresult =
ForEach ($server in $servers) 
{
Set-Service -computername $servers -Name sacsvr -StartupType Disabled -PassThru
}
$result = $subresult 
$result | Out-File local_group_members.csv

This is an example result:

Status   Name               DisplayName                           
------   ----               -----------                           
Stopped  sacsvr             Special Administration Console Helper 
Stopped  sacsvr             Special Administration Console Helper 
Stopped  sacsvr             Special Administration Console Helper 

2 Answers 2

2

Alternatively you can just add a property to the objects you're outputting right now. Pipe your Set-Service to Add-Member like this:

Set-Service -computername $servers -Name sacsvr -StartupType Disabled -PassThru | Add-Member -MemberType NoteProperty -Name 'Server' -Value $Server -PassThru

Now each object that you pass to $subresult has a new property Server that is the name of the server it was run on. You'll probably want to pipe through Select when outputting to have the order you want.

$SubResult | Select Server, Status, Name, DisplayName | Export-CSV 'local_group_members.csv' -NoType
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, its is very helpful. Another question, how can i add something to check if the server is up (like Test-Connection) and put the result also in the Export-CVS of this script?.
That is a little more complicated, and better suited for it's own separate question. You would need to check if the server is up, and then either run Set-Service, and add a member to say that the server is up, or output that the server is down because if it's down running set-service is going to fail.
1

You can arbitrarily re-order or add to your output with Select-Object. You can use hash tables to include calculated properties such as your desired ServerName.

So for each server, you can set the services and tag the output with that server name:

ForEach ($server in $servers) 
{
    Set-Service -computername $server -Name sacsvr -StartupType Disabled -PassThru |
    Select @{Name = 'ServerName'; Expression = {$server}}, Name, DisplayName, Status
}

The above is shorthand for:

Select-Object -Property (properties)

The -Property parameter allows you to select any arbitrary grouping of properties on the type of object being piped in. Another parameter, -InputObject allows us to pipe in objects by value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.