I have the following sample code in a function:
[array]$ARR = $null
foreach ($file in $fileTable.identical)
{
[hashtable]$HT=@{
'FileName' = $file.Name
'AppName' = $file.App
'GroupName' = $file.Group
'Valid' = $true
}
$ARR += $HT
}
foreach ($file in $fileTable.removed)
{
[hashtable]$HT=@{
'FileName' = $file.Name
'AppName' = $file.App
'GroupName' = $file.Group
'Valid' = $false
}
$ARR += $HT
}
foreach ($file in $fileTable.modified)
{
[hashtable]$HT=@{
'FileName' = $file.Name
'AppName' = $file.App
'GroupName' = $file.Group
'Valid' = $false
}
$ARR += $HT
}
return $ARR
+3 more foreach loops for other $fileTable.[properties] where 'Valid' = $false as well.
Instead of having to repeat the block of code multiple times, I want to do something like:
foreach (($file in $fileTable.removed) -and ($file in $fileTable.modified))
{
[hashtable]$HT=@{
'FileName' = $file.Name
'AppName' = $file.App
'GroupName' = $file.Group
'Valid' = $false
}
}
So only variable different in the hashtable will be $value. $fileTable is a pscustomobject with a few custom properties like identical, modified, added, removed.
I know what I want is not possible in foreach loops but I'm looking for a similar solution to reduce the number of lines of code. Any help would be appreciated :)
Thanks!
Combining your and PetSerAls approaches.
Edit: incorporated @mklement0s hint
$ARR = foreach($Variant in 'identical', 'removed', 'modified'){
$fileTable.$Variant | ForEach-Object{
[PSCustomObject]@{
'FileName' = $_.Name
'AppName' = $_.App
'GroupName' = $_.Group
# 'Valid' = if($Variant -eq 'identical'){$True} else {$False}
'Valid' = $Variant -eq 'identical'
}
}
}