通过格式表进行Powershell循环 [英] Powershell Loop through Format-Table
问题描述
我有一个问题. 我创建了一个带有文件名,源目录和目标目录的格式表. 现在,我尝试使用foreach遍历表. 在此循环中,我想将文件从源目录移动到目标目录.我的问题是要从行中获取项目.
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.
这是我的示例代码:
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
}
推荐答案
在处理完数据之前,切勿使用Format-*
-cmdlet.即使这样,也只能在向用户显示某些内容(或创建邮件等)时使用它,因为它们会破坏原始数据,只会给您留下特殊的格式对象.
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.
使用Select-Object
替换Format-Table
,以在保持可用对象的同时获得相同的结果.
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"}
这篇关于通过格式表进行Powershell循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!