在PowerShell中异步移动文件

Raf*_*ski 3 powershell asynchronous powershell-3.0

我有以下问题:我正在编写一个循环,检查文件夹中是否出现某些文件,如果是,则将这些文件移动到另一个文件夹.

该脚本现在运行良好,这是它的代码:

$BasePath = "C:\From"
$TargetPath = "C:\To"
$files = Get-ChildItem -File -Recurse -Path "$($BasePath)\$($Filename)" -ErrorAction SilentlyContinue

foreach ($file in $files)
{
    $subdirectorypath = split-path $file.FullName.Replace($BasePath, "").Trim("\")
    $targetdirectorypath = "$($TargetPath)\$($subdirectorypath)"
    if ((Test-Path $targetdirectorypath) -eq $false)
    {
        Write-Host "Creating directory: $targetdirectorypath"
        md $targetdirectorypath -Force
    }

    Write-Host "Copying file to: $($targetdirectorypath.TrimEnd('\'))\$($File.Name)"
    Move-Item $File.FullName "$($targetdirectorypath.TrimEnd('\'))\$($File.Name)" -Force
}
Run Code Online (Sandbox Code Playgroud)

但是,由于其中一些文件可能非常大,我想以"一劳永逸"的方式异步移动这些文件.使用PowerShell的最佳方法是什么?这个脚本可能会永远运行,因此我认为任何异步作业都必须在完成复制后自行处理.

谢谢你的建议

Mic*_*lli 5

我会使用后台工作:

$scriptblock = {
    $BasePath = $args[0]
    $TargetPath = $args[1]
    $files = Get-ChildItem -File -Recurse -Path "$($BasePath)\$($Filename)" -ErrorAction SilentlyContinue

    foreach ($file in $files)
    {
        $subdirectorypath = split-path $file.FullName.Replace($BasePath, "").Trim("\")
        $targetdirectorypath = "$($TargetPath)\$($subdirectorypath)"
        if ((Test-Path $targetdirectorypath) -eq $false)
        {
            Write-Host "Creating directory: $targetdirectorypath"
            md $targetdirectorypath -Force
        }

        Write-Host "Copying file to: $($targetdirectorypath.TrimEnd('\'))\$($File.Name)"
        Move-Item $File.FullName "$($targetdirectorypath.TrimEnd('\'))\$($File.Name)" -Force
    }
}

$arguments = @("C:\From","C:\To")
start-job -scriptblock $scriptblock -ArgumentList $arguments
Run Code Online (Sandbox Code Playgroud)

如果以后要查看作业的任何输出,可以执行以下操作

Get-Job | Receive-Job
Run Code Online (Sandbox Code Playgroud)