Powershell Loop through Format-Table

送分小仙女□ 提交于 2019-12-08 00:52:20

问题


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
}

回答1:


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"}



回答2:


The format-table cmdlet is to format the output of a command as a table. If you want to work with the objects, use a select instead:

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

Now you can access the properties like you tried in your comment. If you want to print the table, then you can use $table | format-table



来源:https://stackoverflow.com/questions/36999575/powershell-loop-through-format-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!