Hello, I hope I'm not too cheeky to ask the question here... I'm trying to retrieve the local admins group members of all Windows VM servers and export them to a csv. I wrote this code but it only exports to csv one server. So the loop is not correctly set, however I'm new to this -scriptblock feature and I don't know how to append all VMs data:
$winVMS = Get-VM | ?{$_.Guest.GuestFamily -like "win*" -and $_.PowerState -eq "PoweredOn" }
$Credential = Get-Credential
ForEach($vm in $winVMS){
$Computer = $vm + "<domainName>"
Invoke-Command -ComputerName $Computer -Credential $Credential -ScriptBlock {
Get-LocalGroupMember -Group "Administrators"
} | Export-Csv -Path 'C:\Users\xxxxxx\Desktop\localAdmins.csv' -NoTypeInformation
}
Try something like this
Get-VM | Where-Object{$_.Guest.GuestFamily -like "win*" -and $_.PowerState -eq "PoweredOn" } |
ForEach-Object -Process {
Invoke-Command -ComputerName "$($_.Name).<domainname>" -Credential $Credential -ScriptBlock {
Get-LocalGroupMember -Group "Administrators"
}
} | Export-Csv -Path 'C:\Users\xxxxxx\Desktop\localAdmins.csv' -NoTypeInformation -UseCulture
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Try something like this
Get-VM | Where-Object{$_.Guest.GuestFamily -like "win*" -and $_.PowerState -eq "PoweredOn" } |
ForEach-Object -Process {
Invoke-Command -ComputerName "$($_.Name).<domainname>" -Credential $Credential -ScriptBlock {
Get-LocalGroupMember -Group "Administrators"
}
} | Export-Csv -Path 'C:\Users\xxxxxx\Desktop\localAdmins.csv' -NoTypeInformation -UseCulture
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
ehi Master Luc.. thanks first of all! I get
Select-Object : Property "ScriptOutput" cannot be found
I'm on PS 5.1 and PowerCLI 6.5.1 build 5377412, could it be because I need to update something on my side?
I ran your script as is except for the fact that after Get-VM I added two VMs to do a quick test. We have a big environment and to do just a test it would take too long. The precise error is:
Select-Object : Property "ScriptOutput" cannot be found.
At line:10 char:9
+ } | Select-Object -ExpandProperty ScriptOutput | ConvertFrom-Csv
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (xxxx\Domain Admins:PSObject) [Select-Object], PSArgumentException
+ FullyQualifiedErrorId : ExpandPropertyNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand
My bad, I misread, I thought you were using Invoke-VMScript.
I corrected the code above, please give it another try
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thanks again Luc! Flawless..