【问题标题】:Powershell Loop through Format-TablePowershell循环通过格式表
【发布时间】:2016-08-28 05:30:40
【问题描述】:

我有一个问题。 我创建了一个带有文件名、源目录和目标目录的格式表。 现在我尝试用 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
}

【问题讨论】:

    标签: powershell foreach formattable


    【解决方案1】:

    在处理完数据之前,切勿使用Format-*-cmdlet。即使这样,也只能在向用户显示某些内容(或创建邮件等)时使用它,因为它们会破坏原始数据并且只给您留下特殊的格式对象。

    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】:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 2017-05-17
        • 2019-12-21
        • 1970-01-01
        • 2022-08-10
        相关资源
        最近更新 更多