使用Powershell循环遍历Format-Table表格

4

我有一个问题。我创建了一个包含文件名、源目录和目标目录的格式表格。现在我想用foreach循环遍历表格。在这个循环里面,我想把文件从源目录移动到目标目录。我的问题是如何获取行中的项目。

以下是我的示例代码:

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
}
2个回答

9

在完成数据处理之前,不要使用Format-*命令。即使在向用户显示内容(或创建邮件等)时,也只应使用它们,因为它们会破坏原始数据,只留下特殊的格式化对象。

Format-Table替换为Select-Object,以获得相同的结果同时保持可用性。

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

2
< p > format-table cmdlet用于将命令的输出格式化为表格。如果要使用对象,请改用 select

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

现在你可以像在评论中尝试的那样访问属性。如果你想打印表格,那么你可以使用$table | format-table


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接