问题
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