Windows PowerShell 脚本帮助:

Windows PowerShell 脚本帮助:

我需要帮助更改此脚本,我希望它复制一定数量的 Gb,而不是复制一定数量的文件。可能吗?或者随机填充 SD 卡的可用空间(就像 iTunes 那样,直到填满)

#edit this for your settings
$sourceFolder = 'F:\laptop\mp3'
$destFolder = 'F:\random'
$filesToCopy = 4400
$searchFilter = '*.mp3'



function Copy-RandomFiles
{
param (

[Parameter(Mandatory=$true, Position=0)]
[string]$SourceDirectory,

[Parameter(Mandatory=$true, Position=1)]
[string]$DestinationDirectory,

[int]$FilesToCopy = 100,

[string]$SearchFilter = '*.*'
)

$rand = New-Object System.Random

$files = [System.IO.Directory]::GetFiles($SourceDirectory, $SearchFilter, [System.IO.SearchOption]::AllDirectories)

$usedIndexes = @{}
$filteredList = New-Object System.Collections.ArrayList

#build list of random indexes
for([int]$i = 0; ($i -lt $FilesToCopy) -and ($i -lt $files.Length); $i++)
{
    $index = $rand.Next(0, $files.Length)
    #loop till we find an available index
    while($usedIndexes.ContainsKey($index))
    {
        $index = $rand.Next(0, $files.Length)
    }

    $usedIndexes.Add($index, $null)
    $dump = $filteredList.Add($files[$index]) #dump is so it does not display a count
}

if($filteredList.Count -gt 0)
{
    Copy-Item -Path $filteredList.ToArray() -Destination $DestinationDirectory
}

$count = $filteredList.Count

Write-Host "$count file(s) copied"
}

Get-ChildItem $destFolder | Remove-Item
Copy-RandomFiles $sourceFolder $destFolder -FilesToCopy $filesToCopy -SearchFilter $searchFilter

Write-Host "Press any key to continue . . ."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

答案1

您提供的代码不必要地复杂,如下所示:

  1. 复制一定数量的 GB:
$sourceFolder = 'F:\laptop\mp3'
$destFolder = 'F:\random'
$searchFilter = '*.mp3'
$limit = 1GB

[long]$bytesCopied = 0
$count = 0
dir $sourceFolder -Filter $searchFilter | % {
   if($bytesCopied + $_.Length -le $limit) {
      Write-Output "Copying $($_.Name)..."
      Copy $_ $destFolder
      $bytesCopied += $_.Length
      $count++
   }
}
Write-Output "`n$count file(s) ($($bytesCopied) bytes) copied."
  1. 如果您想要复制直到磁盘已满,而不是设置限制,只需将其更改$limit为以下内容:
$limit = (gcim Win32_LogicalDisk -Filter "DeviceID='$($destFolder.Substring(0,2))'").FreeSpace

本质上,这会将您的大小限制更改为目标驱动器上剩余的可用空间量,因此它会继续复制文件,直到驱动器已满。

  1. 如果你想复制随机的从您的源文件集,只需修改“dir”命令如下:
dir $sourceFolder -Filter $searchFilter | Sort {Random} | % {

这将在将文件输入列表传递给循环之前对其进行随机排序。

相关内容