Format-Table in PowerShell inside a ForEach - powershell

Not sure what I am doing wrong here with this, I know it has to do with the fact that it is inside a ForEach loop. I have tried moving the below code around. Even with the code half and half (half in and half out of the loop does not seem to work). Still new to PowerShell and I know that I need to variables to $table each iteration or store them some where and read them later.
foreach ($gp in $GPINFO) {
# Code that gets the values for $gp, $aclBefore and $aclAfter is here
$table = new-object psobject -Property #{
GPO_Name = $gp.DisplayName
Old_Owner = $aclBefore
New_Owner = $aclAfter
}
$table | Format-Table GPO_Name,Old_Owner,New_Owner
}
If you can help me figure out what I am doing wrong that would be great, I know that every time the ForEach gets $gp out of the $GPINFO it is running the $table stuff and that is my problem. So instead of one continuous table I end up with multiple tables with one set of data in each.
Thanks in advance

Just simply output the table after the loop completes.
$table = foreach ($gp in $GPINFO) {
# Code that gets the values for $aclBefore and $aclAfter is here
new-object psobject -Property #{
GPO_Name = $gp.DisplayName
Old_Owner = $aclBefore
New_Owner = $aclAfter
}
}
$table | Format-Table
Any output from within the foreach loop will be stored in $table. Each iteration will output an object, ultimately creating an array of those objects stored in $table.

You just can't pipe from foreach (). It's an odd part of the language that comes up a lot. Other ways:
Foreach-object:
$GPINFO | foreach-object {
$gp = $_
new-object psobject -Property #{
GPO_Name = $gp.DisplayName
Old_Owner = $aclBefore
New_Owner = $aclAfter
}
} | Format-Table GPO_Name,Old_Owner,New_Owner
Call operator and scriptblock:
& {
foreach ($gp in $GPINFO) {
new-object psobject -Property #{
GPO_Name = $gp.DisplayName
Old_Owner = $aclBefore
New_Owner = $aclAfter
}
}
} | Format-Table GPO_Name,Old_Owner,New_Owner

Related

Powershell Pipeline - return a new Object, that was created within pipline

I keep running into the same problem again, and i have my default way of handling it, but it keeps bugging me.
Isn't there any better way?
So basicly i have a pipline running, do stuff within the pipline, and want to return a Key/Value Pair from within the pipline.
I want the whole pipline to return a object of type psobject (or pscustomobject).
Here is the way i do it everytime.
I create a hashtable at the beginning of the pipline and add key/Value Pairs from within the pipline to this hashtable using the .Add() method.
Afterwards i create a psobject by passing the hashtbale to New-Object`s -Property Parameter. This gives me the desired result.
Get-Process | Sort -Unique Name | ForEach-Object -Begin { $ht = #{} } -Process {
# DO STUFF
$key = $_.Name
$val = $_.Id
# Add Entry to Hashtable
$ht.Add($key,$val)
}
# Create PSObject from Hashtable
$myAwesomeNewObject = New-Object psobject -Property $ht
# Done - returns System.Management.Automation.PSCustomObject
$myAwesomeNewObject.GetType().FullName
But this seems a bit cluncky, isn't there a more elegant way of doing it?
Something like this:
[PSObject]$myAwesomeNewObject = Get-Process | Sort -Unique Name | ForEach-Object -Process {
# DO STUFF
$key = $_.Name
$val = $_.Id
# return Key/Val Pair
#{$key=$val}
}
# Failed - returns System.Object[]
$myAwesomeNewObject.GetType().FullName
This unfortunally dosn't work, since the pipe returns an array of hashtables, but i hope you know now what iam trying to achieve.
Thanks
Not sure if this is more elegant but just another way of doing it, this uses an anonymous function so $ht will no longer be available after execution, and casts to [pscustomobject] instead of using New-Object:
[pscustomobject] (Get-Process | Sort -Unique Name | & {
begin { $ht = #{ } }
process {
# DO STUFF
$key = $_.Name
$val = $_.Id
# Add Entry to Hashtable
$ht.Add($key, $val)
}
end { $ht }
})
You can also use the -End parameter to convert the final hash table to a pscustomobject as part of the pipeline, without needing to set the whole thing to a variable
$ht[$key]=$val is also a nice shorthand for $ht.Add($key,$val):
Get-Process |
Sort -Unique Name |
Foreach -Begin { $ht = #{} } -Process {
$ht[$_.Name] = $_.Id
} -End {[pscustomobject]$ht} |
## continue pipeline with pscustomobject
Thanks to #Santiago Squarzon and #Cpt.Whale answers, i were able to combine them to create a solution that pleases me:
$myAwesomeNewObject = `
Get-Process | Sort -Unique Name | & {
begin { $ht = #{} }
process {
# DO STUFF
$key = $_.Name
$val = $_.Id
# Add Entry to Hashtable
$ht[$key]=$val
}
end {[pscustomobject]$ht}
}
# Success - System.Management.Automation.PSCustomObject
$myAwesomeNewObject.Gettype().FullName
# And helper Hashtable is NULL thanks to the
# anonym function
$null -eq $ht
Thanks alot Guys
Alternatively you may create a hashtable using Group-Object -AsHashTable:
# Store the PIDs of all processes into a PSCustomObject, keyed by the process name
$processes = [PSCustomObject] (Get-Process -PV proc |
Select-Object -Expand Id |
Group-Object { $proc.Name } -AsHashtable)
# List all PIDs of given process
$processes.chrome
Notes:
Common parameter -PV (alias of -PipelineVariable) makes sure that we can still access the full process object from within the calculated property of the Group-Object command, despite that we have a Select-Object command in between.
The values of the properties are arrays, which store the process IDs of all instances of each process. E. g. $processes.chrome outputs a list of PIDs of all instances of the chrome process.

How would I store my search results into a table using a foreach loop in powershell?

Import-Module <JAMS>
$JAMSHistories = Get-JAMSHistory -Server TESTDUMMY2 -StartDate "01/20/2020" -EndDate "01/24/2020"
$historyTable = #()
foreach($JAMSHistory in $JAMSHistories)
{
$row = New-Object -TypeName PSObject
Write-Host $JAMSHistory.FinalSeverity
if($JAMSHistory.FinalSeverity -match 'Success')
{
$row | Add-Member -NotePropertyName JobSeveritySuccess ($JAMSHistory.FinalSeverity)
}
else {
if ($JAMSHistory.FinalSeverity -match 'Error') {
$row | Add-Member -NotePropertyName JobSeverityError ($JAMSHistory.FinalSeverity) }
} $historyTable += $row
}
$historyTable
You can do the following, which will output an array of objects ($historyTable) with a properties called JobSeveritySuccess and JobSeverityError.
$JAMSHistories = Get-JAMSHistory -Server TESTDUMMY2 -StartDate "01/20/2020" -EndDate "01/24/2020"
$historyTable = foreach ($JAMSHistory in $JAMSHistories) {
$row = "" | Select JobSeveritySuccess,JobSeverityError
if ($JAMSHistory.FinalSeverity -match 'Success') {
$row.JobSeveritySuccess = $JAMSHistory.FinalSeverity
}
elseif ($JAMSHistory.FinalSeverity -match 'Error') {
$row.JobSeverityError = $JAMSHistory.FinalSeverity
}
$row
}
# Output
$historyTable
# Output in Table Format
$historyTable | Format-Table
The problem with this approach is that every object will have JobSeveritySuccess and JobSeverityError properties, and they may be empty. The only time both properties will have data is if $JAMSHistory.FinalSeverity contains Error and Success for the same object. There is probably a better way to do your design if provided more requirements.
When doing this type of exercise, there are always some gotchas. Consider creating a new PSObject or PSCustomObject for loop iteration. Then output that object at the end of the loop code. When collecting the foreach loop output, just set a variable equal to the foreach loop. There's rarely a need to use += to build an array of foreach loop output. There could be some exceptions to this, but most of the time they are good things to consider.

Sorting and Comparing Arraylists

I'm pretty new to Powershell and have a problem.
It seems I can get neither the Compare-Object nor the Sort-Object funtions to work.
I got two Arraylists which I fill with 10 objects of type "Table".
#Create Arraylists
$list1 = new-object System.Collections.ArrayList
$list2 = new-object System.Collections.ArrayList
#Declare Table-Class
class Table {
[String] $name
[Int] $number
}
#Fill list1
[Int] $i = 0
while ($i -lt 10) {
$entry = new-Object Table
$entry.name = "Name";
$entry.number = $i;
$list1.Add($entry)
$i++
}
#Fill list2
[Int] $j = 10
while ($j -gt 0) {
$entry = new-Object Table
$entry.name = "name";
$entry.number = $j;
$list2.Add($entry)
$j--
}
Now I want to compare these two ArrayLists like this:
Compare-Object $list1 $list2 | ForEach-Object {$_.InputObject}
This doesn't seem to work and I think it's because I'm not really doing anything with the comparison. If someone could help me with the correct Syntax I'd be really happy.
Anyway, I think this comparison would somehow return a $false boolean.
If that were true, I'd like to sort $list2 by $entry.number.
I'm attempting this like that:
$list2 = $list2 | Sort-Object -Property { $_[1] }
But my list doesn't change at all. I already tried several different "solutions" but it seems none of these is a real "solution".
I'd be really glad if someone could help me or at least point me in the right direction.
EDIT: For future readers, here is the working syntax:
#sort list by the property number
$list2 = $list2 | sort-object -Property number
#count differences and if differences greater than 0, do stuff
[Int] $diff
$properties = $list1 | Get-Member -MemberType Property | Select-Object -ExpandProperty Name
foreach ($property in $properties) {
$diff = 0
$diff = (Compare-Object $list1 $list2 -Property "$property").count
if ($diff -ne 0) {
#do stuff
}
else {
#do something else
}
}
Your sorting does not work because -Property expects you to pass the name of an actual property. In your case the class two properties: $name and $number. You can also check what properties an object has by using $list2 | Get-Member. So in order to sort, you can use:
$list2 = $list2 | Sort-Object -Property number
Now the reason Compare-Object is not working is because it's implemented differently that one might expect. See this answer explaining how it works.
One other thing you should keep in mind: Calling $list2.Add($entry) actually returns an integer (the index of the inserted element). PowerShell returns all uncaptured output. This can cause some unexpected behavior/output if you are not careful. So you should get in the habit of writing [void] $list2.Add($entry), unless you really want to return those indexes.

Dynamically creating the name of an existing object to Set one of its properties

I have the following code in Powershell:
function New-Row-Object-Instance {
New-Object PSObject -Property #{
Zeros = 0
Tens = 0
Twentys = 0
Thirtys = 0
Fortys = 0
Fiftys = 0
Sixtys = 0
}
$Row_Details = New-Row-Object-Instance
I Updated $Row_Details with some values. Now I have the following Labels on a Windows Form that is displayed: $Zeros, $Tens, $Twentys, $Thirtys etc.
I want to update the Labels on Form with values using the property Content.
So $Zeros.Content = 2 and so forth
foreach ($property in $Row_Details.PSObject.Properties) {
$property.Name >> $OutFile
# following creates the label names $Zeros,....
$v = -join('$',$property.Name)
# following gives error.. no property named Content
$v.Content = 2
# following gives error.. no property named Content
(-join('$',$property.Name)).Content = 2
# following gives error.. no property named Content
$v | Set-ItemProperty -Name "Content" -Value 2
# following does not update the Labels on the Form itself
Set-Variable $v -Value #{Content = "2"}
# Cannot use Set-ItemProperty -inputObject $v because cannot name property
}
I can hard code name of each Label, but was trying to do it dynamically or Elegantly...
Not sure I really understand your question, but I'll give it a try with a small example that might put you on a track to follow:
$object = New-Object PSObject -Property #{
Zeros = 0;
Tens = 0;
}
$Zeros = New-Object PSObject -Property #{
Content = "0"
}
$Tens = New-Object PSObject -Property #{
Content = "0"
}
$Zeros
$Tens
$object.PSObject.Properties | %{
$property = $_.Name
$expression = "`$$($property).Content = `"2`""
Invoke-Expression $expression
}
$Zeros
$Tens
The question is unclear to me, but maybe this helps
If you just want to modify the values for each of them you an do this:
foreach ($property in $Row_Details.PSObject.Properties)
{
$property.Value = 0
}
If you want to make new variables for each item:
foreach ($property in $Row_Details.PSObject.Properties)
{
New-Variable -Name $property.Name -Value $property.Value
}
You should be able to use Get-Variable for this is interact with those other objects. Shrinking your examples down to two you can proof of concept this fairly easily.
# Simulate your controls by creating object with those respective properties
$Zeros = New-Object PSObject -Property #{Content = 0}
$Tens = New-Object PSObject -Property #{Content = 0}
$Row_Details = New-Object PSObject -Property #{
Zeros = 1
Tens = 2
}
# Display the current Contents
write-host "Zeros: $($Zeros.Content)"
write-host "Tens: $($Tens.Content)"
foreach ($property in $Row_Details.PSObject.Properties){
$singleVariable = Get-Variable $property.name
$singleVariable.Value.content = $property.Value
}
# Show the updated Contents
write-host "Zeros: $($Zeros.Content)"
write-host "Tens: $($Tens.Content)"
The results of this being
Zeros: 0
Tens: 0
Zeros: 1
Tens: 2
The only problem I see is that all of this exists in the same scope so you my example should work as intended. However, depending where your variables are defined, you might have scope issues. If that happens you just need to experiment with the -Scope parameter of Get-Variable

Can't display PSObject

I'm trying to display some data my script generates in a PSObject, so I can then export to a CSV, but the only object that shows is whichever one I add to the array first.
$pass=#("1","2","3")
$fail=#("4")
$obj=#()
$pass | % {
$obj+=New-Object PSObject -Property #{Pass=$_}
}
$fail | % {
$obj+=New-Object PSObject -Property #{Fail=$_}
}
$obj
I've also tried this, but I get a blank line showing in the table where the value isn't in that column, which I don't want:
$pass=#("1","2","3")
$fail=#("4")
$obj=#()
$pass | % {
$obj+=New-Object PSObject -Property #{Pass=$_;Fail=""}
}
$fail | % {
$obj+=New-Object PSObject -Property #{Pass="";Fail=$_}
}
$obj
My desired result:
Pass Fail
---- ----
1 4
2
3
I am using Powershell V2.
Another answer is right - you're using objects wrong. That being said, here's a function to help you use them wrong!
Function New-BadObjectfromArray($array1,$array2,$array1name,$array2name){
if ($array1.count -ge $array2.count){$iteratorCount = $array1.count}
else {$iteratorCount = $array2.count}
$obj = #()
$iteration=0
while ($iteration -le $iteratorCount){
New-Object PSObject -Property #{
$array1name=$array1[$iteration]
$array2name=$array2[$iteration]
}
$iteration += 1
}
$obj
}
$pass=#("1","2","3")
$fail=#("4")
New-BadObjectfromArray -array1 $fail -array2 $pass -array1name "Fail" -array2name "Pass"
As you figured out yourself, PowerShell only outputs the properties of the first item in your array. Its not designed to print the ouput you are expecting in the way you are using it.
As a workaround, you could use a for loop to "build" your desired output:
$pass=#("1","2","3")
$fail=#("4")
$obj=#()
for ($i = 0; $i -lt $pass.Count; $i++)
{
if ($fail.Count -gt $i)
{
$currentFail = $fail[$i]
}
else
{
$currentFail = ""
}
$obj+=New-Object PSObject -Property #{Fail=$currentFail;Pass=$pass[$i];}
}
$obj | select Pass, Fail
Output:
Pass Fail
---- ----
1 4
2
3