2016-01-31 26 views
0

此代碼將使用一個Shell.Application COM對象並使用本機Windows複製對話框將項目複製到指定的目標。唯一的問題是,對於源代碼中的每個直接子文件夾,它將創建單獨的複製對話框。使用GUI變體複製文件夾項目

有隻得到1個對話顯示任何方式對我來說,這樣用戶就可以看到準確的信息,如整體進度,剩餘時間等

我到目前爲止想到的最簡單的事情是或者將文件壓縮後在源文件中解壓縮(請不要),或者複製整個父項,然後將子項移到原位,但我覺得這會限制函數的功能。

任何人都可以想到一個很好的解決方案嗎?

function Copy-ItemGUI { 
    Param(
     # TODO: Allow only folder paths (Can we test these here and loop if 
     # path is invalid?) 
     [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] 
     $Source, 

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

    #If destination does not exist, break 
    #TODO: Create folder if destination does not exist 
    if (!(Test-Path $Destination)) { 
     break 
    } 

    $src = gci $Source 

    $objShell = New-Object -ComObject "Shell.Application" 

    $objFolder = $objShell.NameSpace($Destination) 

    $counter = ($src.Length) - 1 
    foreach ($file in $src) { 
     Write-Host -ForegroundColor Cyan "Copying file '"$file.name"' to ' $Destination '" 

     try { 
      #Info regarding options for displayed info during shell copy - https://technet.microsoft.com/en-us/library/ee176633.aspx 
      $objFolder.CopyHere("$source\$file", "&H0&") 
     } catch { 
      Write-Error $_ 
     } 

     Write-Host -ForegroundColor Green "Copy complete - Number of items remaining: $counter`n" 
     $counter-- 
    } 
} 
+0

請不要鏈接到非現場代碼。始終在您的問題中包含[MCVE](http://stackoverflow.com/help/mcve)。 –

回答

0

不要枚舉$source的內容並單獨複製每個文件。使用通配符指定要複製的項目。將您的功能更改爲:

function Copy-ItemGUI { 
    Param(
     [Parameter(
      Mandatory=$true, 
      Position=0, 
      ValueFromPipeline=$true, 
      ValueFromPipelineByPropertyName=$true 
     )] 
     [ValidateScript({Test-Path -LiteralPath $_})] 
     [string[]]$Source, 

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

    Begin { 
     if (-not (Test-Path -LiteralPath $Destination)) { 
      New-Item -Type Directory $Destination | Out-Null 
     } 

     $objShell = New-Object -ComObject 'Shell.Application' 
     $objFolder = $objShell.NameSpace($Destination) 
    } 

    Process { 
     $objFolder.CopyHere("$source\*", '&H0&') 
    } 
} 
相關問題