Reputation: 23
I hope someone can point me in the correct direction. I've written a script that will search directories and list files found. I want to display this using format-table but I'm struggling to understand how to collect the results correctly in an object as there will be repeating keys and values.
The below script will only work for the first file found - I assume because it is re-adding members with the same name of file and directory.
I've spent days trying to work this out and reading all I can, and I just don't understand. I would very much appreciate being sent in the right direction.
Many thanks for any help. I should also mention that I am stuck using v1.
$servers = @{
"1" = @(
"C:\a","C:\b"
)
}
foreach ($h in $servers.GetEnumerator()) {
$d = @($h.Value)
foreach ($dir in $d) {
if (!(Test-Path -Path $dir)) {
Write-Host $($h.Name)
Write-Host $dir" DOES NOT EXIST"
} else {
$file = Get-ChildItem "$dir" -recurse | Where-Object {$_ -is [IO.FileInfo]}
if (!($file -eq $null)) {
Write-Host $($h.Name)
$result = New-Object PSObject
foreach ($f in $file) {
$result | Add-Member -MemberType NoteProperty Directory -Value $f.directory
$result | Add-Member -MemberType NoteProperty File -Value $f.name
}
}
Write-Output ($result | Format-Table | Out-String)
}
}
}
Upvotes: 2
Views: 1159
Reputation: 3361
You're alomst there :-) You're creating an object for each file you find. However, you need to store all those objects somewhere ($result basically gets overwritten each time you find a file so it's only valid inside the loop). What you need to do is to send each "instance" of $result to some other place. If you compare my suggestion with yours you'll see that the only difference is that i've moved the "new-psobject" call to inside the foreach file loop, and added an array to actually store the results. BTW, I cannot stress enough that PowerShell has a very good debugging story allowing you to basically step thru code like this. Take the time learn how to use it and you won't get stuck on stuff like this :-)
foreach ($h in $servers.GetEnumerator()) {
$d = @($h.Value)
$resultarray = @()
foreach ($dir in $d) {
if (!(Test-Path -Path $dir)) {
Write-Host $($h.Name)
Write-Host $dir" DOES NOT EXIST"
} else {
$file = Get-ChildItem "$dir" -recurse -ErrorAction 0 | Where-Object {$_ -is [IO.FileInfo]}
if (!($file -eq $null)) {
Write-Host $($h.Name)
foreach ($f in $file) {
$result = New-Object PSObject
$result | Add-Member -MemberType NoteProperty Directory -Value $f.directory
$result | Add-Member -MemberType NoteProperty File -Value $f.name
$resultarray += $result; $result=$null
}
}
Write-Output ($resultarray | Format-Table | Out-String)
}
}
}
Upvotes: 2