create an object from returned variables of a foreach powershell
10,137
You're probably better off creating multiple objects, one per computer, inside the foreach
loop.
# Loop through machines, assign all output to $Objects variable
$Objects = foreach ($Machine in $Machines)
{
#where i make a process foreach computer and there are variables that are returned
{
}
###############################
#where i am trying to append to the created object the returned variables
# Define the properties that the object should have in a hashtable
$ObjectProperties = @{
# Assuming you've assigned something to $Propriedad, $Users and $ErrorState above
Propiedad = $Propriedad
Users = $Users
Computer = $Machine
Error = $ErrorState
}
# Now create an object.
# When we just drop it in the pipeline like this, it gets assigned to $Objects
New-Object psobject -Property $ObjectProperties
}
Now you can create HTML from your objects with ConvertTo-Html
:
$Objects | ConvertTo-Html -As Table -Head "<title>Kimo's report</title>"
If you want to test it, you'll need to change $Machines
to:
"pc1","pc2","pc3","pc4","pc5","pc6","pc7","pc8","pc9","pc0"
If you want to save this as a .ps1 script file and be able to pass the computer names as arguments, add a param()
block at the top:
param([string[]]$Machines)
Now, if you save the script as "KimosReporter.ps1", you can run it against any computer like this:
PS C:\>.\KimosReporter.ps1 -Machines "pc1","pc6","pc9"
Comments
-
kimo pryvt almost 2 years
I am trying to create a script that receives a list of computers and for-each computer I need to create a process, after running the process, I have many variables that y need to append to a an object
How can I append to the object, the returned info of the pcs?
#input variable that the foreach need to process $Machines = "pc1,pc2,pc3,pc4,pc5,pc6,pc7,pc8,pc9,pc0" #create empty object $pcNull $MachineNull $usersNull $object= New-Object Object $object | Add-Member NoteProperty propiedad $MachineNull $object | Add-Member NoteProperty users $usersNull $object | Add-Member NoteProperty computer $pcNull $object | Add-Member NoteProperty error $false foreach ($Machine in $Machines ) { #where i make a process foreach computer and there are variables that are returned { } ############################### #where i am trying to append to the created object the returned variables #append to propiedad property $object.propiedad = $object.propiedad = $MachineNull $object #append to users property $object.users = $object.users = $false $object #append to computers property $object.computer = $object.computer = $Machine $object } $object