Powershell Loop through Format-Table

Alexander Hadula picture Alexander Hadula · May 3, 2016 · Viewed 9.8k times · Source

I've got a question. I've created a format-table with filename, source- and destination directory. Now I try to loop through the table with a foreach. Inside this loop i want to move the files from the source- to destination directory. My problem is to get the items from the row.

Here is my example code:

cls
$MovePathSource = "C:\Users\user\Desktop\sourcefolder"
$MovePathDestination = "C:\Users\user\Desktop\destinationfolder"

$filetypes = @("*.llla" , "html")
$table = dir $MovePathSource -Recurse -Include $filetypes | Format-Table@{Expression={$_.Name};Label="Filename"},@{Expression={($_.DirectoryName)};Label="Sourcepath"},@{Expression={($_.DirectoryName).Replace($MovePathSource,$MovePathDestination)};Label="Destinationpath"}

$table

foreach ($row in $table)
{
write-host "$row.Sourcepath"
#Move-Item -Path ($row.Sourcepath + "\" + $row.Filename) -Destination $row.Destinationpath
}

Answer

Frode F. picture Frode F. · May 3, 2016

Never use Format-*-cmdlets before your done with the data. Even then, only use it when displaying something to a user (or creating a mail etc.) as they break the original data and only leave you with special format-objects.

Replace Format-Table With Select-Object to get the same result while keeping usable objects.

$table = dir $MovePathSource -Recurse -Include $filetypes |
Select-Object @{Expression={$_.Name};Label="Filename"},@{Expression={($_.DirectoryName)};Label="Sourcepath"},@{Expression={($_.DirectoryName).Replace($MovePathSource,$MovePathDestination)};Label="Destinationpath"}