We help IT Professionals succeed at work.
Troubleshooting Question

Change part of a Powershell script to show a Source and Destination

38 Views
Last Modified: 2020-09-10
I would like to change the portion of a Powershell script below to include the Source of
C:\Users\User\Desktop and the destination of C:\\vm1\Backups\User\Desktop

How can this be changed?
Thanks in advance.

I added the complete script now..
function robocopy-job  
{ 
    [CmdletBinding()] 
 
    param ( 
            [Parameter(Mandatory = $true)] 
            [string] $Source 
        , [Parameter(Mandatory = $true)] 
            [string] $Destination) 
 
    $robocopycmd = "robocopy ""$source"" ""$destination"" /mir /bytes" 
    $Staging = Invoke-Expression "$robocopycmd /l" 
    $totalnewfiles = $Staging -match 'new file' 
    $totalmodified = $Staging -match 'newer' 
    $totalfiles = $totalnewfiles + $totalmodified
    $TotalBytesarray = @()
    foreach ($file in $totalfiles)  
    { 
        if ($file.substring(13,13).trim().length -eq 9) {$TotalBytesarray+= $file.substring(13,15).trim() } 
        else {$TotalBytesarray+= $file.substring(13,13).trim()} 
    } 
    $totalbytes = (($TotalBytesarray | Measure-Object -Sum).sum)
 
    $robocopyjob = Start-Job -Name robocopy -ScriptBlock {param ($command) ; Invoke-Expression -Command $command} -ArgumentList $robocopycmd 
 
    while ($robocopyjob.State -eq 'running') 
    { 
        $progress = Receive-Job -Job $robocopyjob -Keep -ErrorAction SilentlyContinue
      if ($progress)
      {
         $copiedfiles = ($progress | Select-String -SimpleMatch 'new file', 'newer')
         if ($copiedfiles.count -le 0) { $TotalFilesCopied = $copiedfiles.Count }
         else { $TotalFilesCopied = $copiedfiles.Count - 1 }
         $FilesRemaining = ($totalfiles.count - $TotalFilesCopied)
         $Bytesarray = @()
         foreach ($Newfile in $copiedfiles)
         {
            if ($Newfile.tostring().substring(13, 13).trim().length -eq 9) { $Bytesarray += $Newfile.tostring().substring(13, 15).trim() }
            else { $Bytesarray += $Newfile.tostring().substring(13, 13).trim() }
         }
         $bytescopied = ([int64]$Bytesarray[-1] * ($Filepercentcomplete/100))
         $totalfilebytes = [int64]$Bytesarray[-1]
         $TotalBytesCopied = ((($Bytesarray | Measure-Object -Sum).sum) - $totalfilebytes) + $bytescopied
         $TotalBytesRemaining = ($totalbytes - $totalBytesCopied)
         if ($copiedfiles)
         {
            if ($copiedfiles[-1].tostring().substring(13, 13).trim().length -eq 9) { $currentfile = $copiedfiles[-1].tostring().substring(28).trim() }
            else { $currentfile = $copiedfiles[-1].tostring().substring(25).trim() }
         }
         $totalfilescount = $totalfiles.count
         if ($progress[-1] -match '%') { $Filepercentcomplete = $progress[-1].substring(0, 3).trim() }
         else { $Filepercentcomplete = 0 }
         $totalPercentcomplete = (($TotalBytesCopied/$totalbytes) * 100)
         if ($totalbytes -gt 2gb) { $BytesCopiedprogress = "{0:N2}" -f ($totalBytesCopied/1gb); $totalbytesprogress = "{0:N2}" -f ($totalbytes/1gb); $bytes = 'Gbytes' }
         else { $BytesCopiedprogress = "{0:N2}" -f ($totalBytesCopied/1mb); $totalbytesprogress = "{0:N2}" -f ($totalbytes/1mb); $bytes = 'Mbytes' }
         if ($totalfilebytes -gt 1gb) { $totalfilebytes = "{0:N2}" -f ($totalfilebytes/1gb); $bytescopied = "{0:N2}" -f ($bytescopied/1gb); $filebytes = 'Gbytes' }
         else { $totalfilebytes = "{0:N2}" -f ($totalfilebytes/1mb); $bytescopied = "{0:N2}" -f ($bytescopied/1mb); $filebytes = 'Mbytes' }
         
         Write-Progress -Id 1 -Activity "Copying files from $source to $destination, $totalfilescopied of $totalfilescount files copied" -Status "$bytescopiedprogress of $totalbytesprogress $bytes copied" -PercentComplete $totalPercentcomplete
         Write-Progress -Id 2 -Activity "$currentfile" -status "$bytescopied of $totalfilebytes $filebytes" -PercentComplete $Filepercentcomplete
      }
      
   }
   
   Write-Progress -Id 1 -Activity "Copying files from $source to $destination" -Status 'Completed' -Completed 
    Write-Progress -Id 2 -Activity 'Done' -Completed 
    $results = Receive-Job -Job $robocopyjob 
    Remove-Job $robocopyjob 
    $results[5] 
    $results[-13..-1] 
} 
Comment
Watch Question

AlexA lack of information provides a lack of a decent solution.
CERTIFIED EXPERT

Commented:
$Source = C:\Users\User\Desktop
$Destination = C:\vm1\Backups\User\Desktop

function robocopy-job  
{     [CmdletBinding()]  
    param (             [Parameter(Mandatory = $true)]             [string] $Source         , [Parameter(Mandatory = $true)]             [string] $Destination)  
    $robocopycmd = "robocopy ""$source"" ""$destination"" /mir /bytes" 

Should do it from my understanding
Or replace $Source and $Destination with their respective locations


Author

Commented:
Thanks.. I will try this.. 
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks oBaA..., I now added the complete script so that it's easier to discern if this will work.
Will your suggestion work with the complete script that I updated?
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
Yes, that will work (assuming that the function itself works).
Just be aware that this function will mirror the source to the destination, which means it will delete anything in destination that is not in source (anymore).

Author

Commented:
Thanks oBdA, I will try it..
Just wondering though where is the last line with the command placed, right at the end of the long script?

This one?
robocopy-job -Source 'C:\Users\User\Desktop' -Destination 'C:\vm1\Backups\User\Desktop'
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
After the function's closing curly bracket, so below line 71 in the script above.

Author

Commented:
Thanks oBdA, let me give it a try.. many thanks.. 

Author

Commented:
oBdA, it worked actually.
In my test I did get an error message however, but it doesn't seem like a major error message..
It said..

Write-Progress : Cannot bind argument to parameter 'Activity' because it is an empty string.
At C:\Users\User\Desktop\Scrips\Script.ps1:60 char:35
+             Write-Progress -Id 2 -Activity "$currentfile" -status "$b ...
+                                            ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Write-Progress], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.WriteProgressCommand
 
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
That can be safely ignored.
You're aware that the "copy" functionality of this function is just a simple
& robocopy.exe "`"$($source)`"" "`"$($destination)` "" /mir /bytes

Open in new window

The rest is just trying to parse the output to create a progress bar.
On the downside, it doesn't check robocopy's errorlevel, so you can't really tell if files failed to copy or not ...

Author

Commented:
Thanks oBDa..
The display tells me if all files were copied or not doesn't it?
Yes I am aware of the function being a complete mirror of the source.
So if it's looking for the $source and the $desination early in the script..  shouldn't I be specifying them early in the script somewhere too?
CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
It's a function. It just gets loaded and is then available for use, like one of the standard cmdlets.
And when you call it, you pass the parameters, like you'd do for Get-ChildItem or whatever else.

Author

Commented:
Thank you oBdA..

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.