通过PowerShell控制任何进程的网络速度?

时间:2015-03-25 13:29:58

标签: powershell

我使用PowerShell进行文件夹同步。我的问题是“Copy-Item”如何使用网络带宽/速度?它是否使用所有可用带宽?或者由Windows自动控制。

因为我的同步过程将通过vpn执行,所以我想将同步速度控制到500K,是否可以在powershell中执行,如同this software那样?

function Get-FileMD5 {
    Param([string]$file)
    $md5 = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
    $IO = New-Object System.IO.FileStream($file, [System.IO.FileMode]::Open)
    $StringBuilder = New-Object System.Text.StringBuilder
    $md5.ComputeHash($IO) | % { [void] $StringBuilder.Append($_.ToString("x2")) }
    $hash = $StringBuilder.ToString() 
    $IO.Dispose()
    return $hash
}
#VARIABLES
$DebugPreference = "continue"
#parameters
$SRC_DIR = 'VPN POINT'
$DST_DIR = 'VPN POINT'
#SCRIPT MAIN
clear
$SourceFiles = GCI -Recurse $SRC_DIR | ? { $_.PSIsContainer -eq $false} #get the files in the source dir.
$SourceFiles | % { # loop through the source dir files
    $src = $_.FullName #current source dir file
    Write-Debug $src
    $dest = $src -replace $SRC_DIR.Replace('\','\\'),$DST_DIR #current destination dir file
    if (test-path $dest) { #if file exists in destination folder check MD5 hash
        $srcMD5 = Get-FileMD5 -file $src
        Write-Debug "Source file hash: $srcMD5"
        $destMD5 = Get-FileMD5 -file $dest
        Write-Debug "Destination file hash: $destMD5"
        if ($srcMD5 -eq $destMD5) { #if the MD5 hashes match then the files are the same
            Write-Debug "File hashes match. File already exists in destination folder and will be skipped."
            $cpy = $false
        }
        else { #if the MD5 hashes are different then copy the file and overwrite the older version in the destination dir
            $cpy = $true
            Write-Debug "File hashes don't match. File will be copied to destination folder."
        }
    }
    else { #if the file doesn't in the destination dir it will be copied.
        Write-Debug "File doesn't exist in destination folder and will be copied."
        $cpy = $true
    }
    Write-Debug "Copy is $cpy"
    if ($cpy -eq $true) { #copy the file if file version is newer or if it doesn't exist in the destination dir.
        Write-Debug "Copying $src to $dest"
        if (!(test-path $dest)) {
            New-Item -ItemType "File" -Path $dest -Force   
        }
        Copy-Item -Path $src -Destination $dest -Force
    }
}

2 个答案:

答案 0 :(得分:2)

Visual Studio 2010中有一个Network Emulator功能(可能更新)。也许你可以从PowerShell开始工作。否则我认为你将不得不诉诸NetLimiter或其中一个替代方案:

答案 1 :(得分:0)

Robocopy确实具备这种能力,你可以通过Invoke-Expression将它包装在PowerShell中。