首页 > 解决方案 > 将写入进度条添加到脚本 Powershell

问题描述

我实际上正在编写一个按日期对图片和视频进行排序的 powershell 脚本。该脚本工作正常,但我想添加一个进度条,我不知道从哪里开始,这对我来说可能有点棘手,这就是我寻求帮助的原因。

这是对图片进行排序的功能

foreach ($file in $Images) 
{
    $Directory = $destinationDirectory + "Pictures\" + $file.LastWriteTime.Date.ToString('yyyy') + "\" + $file.LastWriteTime.Date.ToString('MMM') 

if (!(Test-Path $Directory))
{

    New-Item $directory -type directory
}

Copy-Item $file.fullname $Directory 
}

我阅读了有关写入进度功能的文档,但我真的不知道我应该如何在这个脚本中管理它

标签: powershell

解决方案


使用一个变量来保存复制文件的数量,为每个操作增加它,然后显示百分比。Write-Progress的例子有一个很好的例子。

我建议也使用 PowerShell 管道,而不是foreach.

像这样的东西(-WhatIf准备好后删除 s):

$images |
    ForEach-Object 
    -Begin { 
        $filesCopied = 0
    } `
    -Process {
        $Directory = "$destinationDirectory\Pictures\$($_.LastWriteTime.Date.ToString('yyyy'))\$($_.LastWriteTime.Date.ToString('MMM'))"

        if (!(Test-Path $Directory)) {
            New-Item $directory -type directory -WhatIf
        }

        Copy-Item $_.fullname $Directory -WhatIf

        $filesCopied += 1
        Write-Progress -Activity "Copied $_.FullName" `
            -CurrentOperation "Copying $_" `
            -Status "Progress:" `
            -PercentComplete (($filesCopied / $Images.Count) * 100)
    }

推荐阅读