简体   繁体   中英

How do I fix this Robocopy error in Windows Powershell?

Good-day,

While following a tutorial posted by @Trevor Sullivan in response to this question , I'm unable to get the script to work. It's failing, citing that it cannot find the log file. At first I thought it may have been a permissions issue, so I explicitly specified the file path for the log file, and I'm still getting the same error message.

How do I fix the code so that it runs?

HERE'S THE CODE:

function Copy-WithProgress {
    [CmdletBinding()]
    param (
            [Parameter(Mandatory = $true)]
            [string] $Source
        , [Parameter(Mandatory = $true)]
            [string] $Destination
        , [int] $Gap = 0
        , [int] $ReportGap = 2000
    )
    # Define regular expression that will gather number of bytes copied
    $RegexBytes = '(?<=\s+)\d+(?=\s+)';

    #region Robocopy params
    # MIR = Mirror mode
    # NP  = Don't show progress percentage in log
    # NC  = Don't log file classes (existing, new file, etc.)
    # BYTES = Show file sizes in bytes
    # NJH = Do not display robocopy job header (JH)
    # NJS = Do not display robocopy job summary (JS)
    # TEE = Display log in stdout AND in target log file
    $CommonRobocopyParams = '/MIR /COPYALL /DCOPY:T /SECFIX /NP /NDL /NC /BYTES /NJH /NJS';
    #endregion Robocopy params

    #region Robocopy Staging
    Write-Verbose -Message 'Analyzing robocopy job ...';
    $StagingLogPath = '{0}\Temp\{1} robocopy staging.log' -f $env:windir, (Get-Date -Format 'yyyy-MM-dd hh-mm-ss');

    $StagingArgumentList = '"{0}" "{1}" /LOG:"{2}" /L {3}' -f $Source, $Destination, $StagingLogPath, $CommonRobocopyParams;
    Write-Verbose -Message ('Staging arguments: {0}' -f $StagingArgumentList);
    Start-Process -Wait -FilePath robocopy.exe -ArgumentList $StagingArgumentList -NoNewWindow;
    # Get the total number of files that will be copied
    $StagingContent = Get-Content -Path $StagingLogPath;
    $FileCount = $StagingContent.Count;

    # Get the total number of bytes to be copied
    [RegEx]::Matches(($StagingContent -join "`n"), $RegexBytes) | % { $BytesTotal = 0; } { $BytesTotal += $_.Value; };
    Write-Verbose -Message ('Total bytes to be copied: {0}' -f $BytesTotal);
    #endregion Robocopy Staging

    #region Start Robocopy
    # Begin the robocopy process
    $RobocopyLogPath = '{0}\Temp\{1} robocopy.log' -f $env:windir, (Get-Date -Format 'yyyy-MM-dd hh-mm-ss');
    $ArgumentList = '"{0}" "{1}" /LOG:"{2}" /ipg:{3} {4}' -f $Source, $Destination, $RobocopyLogPath, $Gap, $CommonRobocopyParams;
    Write-Verbose -Message ('Beginning the robocopy process with arguments: {0}' -f $ArgumentList);
    $Robocopy = Start-Process -FilePath robocopy.exe -ArgumentList $ArgumentList -Verbose -PassThru -NoNewWindow;
    Start-Sleep -Milliseconds 100;
    #endregion Start Robocopy

    #region Progress bar loop
    while (!$Robocopy.HasExited) {
        Start-Sleep -Milliseconds $ReportGap;
        $BytesCopied = 0;
        $LogContent = Get-Content -Path $RobocopyLogPath;
        $BytesCopied = [Regex]::Matches($LogContent, $RegexBytes) | ForEach-Object -Process { $BytesCopied += $_.Value; } -End { $BytesCopied; };
        Write-Verbose -Message ('Bytes copied: {0}' -f $BytesCopied);
        Write-Verbose -Message ('Files copied: {0}' -f $LogContent.Count);
        Write-Progress -Activity Robocopy -Status ("Copied {0} files; Copied {1} of {2} bytes" -f $LogContent.Count, $BytesCopied, $BytesTotal) -PercentComplete (($BytesCopied/$BytesTotal)*100);
    }
    #endregion Progress loop

    #region Function output
    [PSCustomObject]@{
        BytesCopied = $BytesCopied;
        FilesCopied = $LogContent.Count;
    };
    #endregion Function output
}

# Call the Copy-WithProgress function
Copy-WithProgress -Source "M:\" -Destination "E:\Homes" -Verbose;

HERE'S THE ERROR:

PS C:\Users\Administrator> C:\Users\Administrator\Documents\PowerShell Scripts\Copy_With_Progress.ps1
VERBOSE: Analyzing robocopy job ...
VERBOSE: Staging arguments: "M:\" "E:\Homes" /LOG:"C:\Windows\Temp\2014-09-29 02-11-54 robocopy staging.lo
g" /L /MIR /COPYALL /DCOPY:T /SECFIX /NP /NDL /NC /BYTES /NJH /NJS
Get-Content : Cannot find path 'C:\Windows\Temp\2014-09-29 02-11-54 robocopy staging.log' because it
does not exist.
At C:\Users\Administrator\Documents\PowerShell Scripts\Copy_With_Progress.ps1:33 char:23
+     $StagingContent = Get-Content -Path $StagingLogPath;
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Windows\Temp...opy staging.log:String) [Get-Content],  
   ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

VERBOSE: Total bytes to be copied: 0
VERBOSE: Beginning the robocopy process with arguments: "M:\" "E:\Homes" /LOG:"C:\Windows\Temp\2014-09-29
02-11-55 robocopy.log" /ipg:0 /MIR /COPYALL /DCOPY:T /SECFIX /NP /NDL /NC /BYTES /NJH /NJS
Get-Content : Cannot find path 'C:\Windows\Temp\2014-09-29 02-11-55 robocopy.log' because it does not
exist.
At C:\Users\Administrator\Documents\PowerShell Scripts\Copy_With_Progress.ps1:54 char:23
+         $LogContent = Get-Content -Path $RobocopyLogPath;
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Windows\Temp...55 robocopy.log:String) [Get-Content],  
   ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Exception calling "Matches" with "2" argument(s): "Value cannot be null.
Parameter name: input"
At C:\Users\Administrator\Documents\PowerShell Scripts\Copy_With_Progress.ps1:55 char:9
+         $BytesCopied = [Regex]::Matches($LogContent, $RegexBytes) | ForEach-Obje ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

VERBOSE: Bytes copied: 0
VERBOSE: Files copied: 0
Attempted to divide by zero.
At C:\Users\Administrator\Documents\PowerShell Scripts\Copy_With_Progress.ps1:58 char:9
+         Write-Progress -Activity Robocopy -Status ("Copied {0} files; Copied {1} ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : NotSpecified: (:) [], RuntimeException
   + FullyQualifiedErrorId : RuntimeException


                                        BytesCopied                                          FilesCopied
                                        -----------                                          -----------
                                                  0                                                    0



PS C:\Users\Administrator> C:\Users\Administrator\Documents\PowerShell Scripts\Copy_With_Progress.ps1
VERBOSE: Analyzing robocopy job ...
VERBOSE: Staging arguments: "M:\" "E:\Homes" /LOG:"E:\Logs\2014-09-29 02-16-10 r
obocopy staging.log" /L /MIR /COPYALL /DCOPY:T /SECFIX /NP /NDL /NC /BYTES /NJH
/NJS
Get-Content : Cannot find path 'E:\Logs\2014-09-29 02-16-10 robocopy
staging.log' because it does not exist.
At C:\Users\Administrator\Documents\PowerShell
Scripts\Copy_With_Progress.ps1:33 char:23
+     $StagingContent = Get-Content -Path $StagingLogPath;
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : ObjectNotFound: (E:\Logs\2014-09...opy staging.l
  og:String) [Get-Content], ItemNotFoundException
   + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo
  ntentCommand

VERBOSE: Total bytes to be copied: 0
VERBOSE: Beginning the robocopy process with arguments: "M:\" "E:\Homes" /LOG:"E
:\Logs\2014-09-29 02-16-11 robocopy.log" /ipg:0 /MIR /COPYALL /DCOPY:T /SECFIX /
NP /NDL /NC /BYTES /NJH /NJS
Get-Content : Cannot find path 'E:\Logs\2014-09-29 02-16-11 robocopy.log'
because it does not exist.
At C:\Users\Administrator\Documents\PowerShell
Scripts\Copy_With_Progress.ps1:54 char:23
+         $LogContent = Get-Content -Path $RobocopyLogPath;
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : ObjectNotFound: (E:\Logs\2014-09-29 02-16-11 rob
  ocopy.log:String) [Get-Content], ItemNotFoundException
   + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo
  ntentCommand

Exception calling "Matches" with "2" argument(s): "Value cannot be null.
Parameter name: input"
At C:\Users\Administrator\Documents\PowerShell
Scripts\Copy_With_Progress.ps1:55 char:9
+         $BytesCopied = [Regex]::Matches($LogContent, $RegexBytes) |
ForEach-Obje ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
   + FullyQualifiedErrorId : ArgumentNullException

VERBOSE: Bytes copied: 0
VERBOSE: Files copied: 0
Attempted to divide by zero.
At C:\Users\Administrator\Documents\PowerShell
Scripts\Copy_With_Progress.ps1:58 char:9
+         Write-Progress -Activity Robocopy -Status ("Copied {0} files; Copied
{1} ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException


                            BytesCopied                             FilesCopied
                            -----------                             -----------
                                      0                                       0



PS C:\Users\Administrator>

Looking at your code it's almost like somebody escaped it with backslashes. Replace all of the \\\\ with \\ and replace the \\' with ' . See if that doesn't fix your issue.

Isolate the Get-Content line and test using the literal path. If this still fails, try adding -Force switch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM