can i force overwrite a file and its subdirectories from uncpath using powershell?

As announced, here my comments as answer.

Startup scripts are run under the Local System account, and have the full rights that are associated with being able to run under the Local System account, there should be no problem with registry or file permissions.
The script is run on the local computer, so in that case you can simply use a local path for the destination instead of creating a UNC path for that.

Because copying speed is essential in a startup script, I would not use the Copy-Item cmdlet here, but rather use RoboCopy.

$computer       = $env:COMPUTERNAME
$domain         = $env:USERDNSDOMAIN
$source         = "\\FILESVR01\IT\Custom Application\Modules"
$destination    = "C:\Program Files (x86)\Custom Application\Modules"
$RunTimeVersion = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client" -Name Version).Version

If ((Test-Path -Path $destination -PathType Container) -and ($RunTimeVersion -gt [Version]3.5)) {
    Try {
        & robocopy "$source" "$destination" /MIR /IS /IT /W:1 /R:1
        Write-Host "Sucessfully copied on $($computer)" -BackgroundColor Green
        # maybe you want to send a mail on success aswell?
        $body = "Sucessfully copied files on $($computer)"
        # if not, just set the $body variable to $null
    }
    Catch {
        Write-Host $_.Exception.Message -ForegroundColor Red
        $body = "Error copying files to $($computer):<p>$($_.Exception.Message)</p>"
    }
}
else {
    $body = "Target folder '$destination' on $($computer) not found or not accessible or installed version $($RunTimeVersion) less than 3.5"
    Write-Host $body -ForegroundColor Red
}

if ($body) {
    $mailArgs = @{
        From       = "$env:[email protected]$domain"
        To         = "[email protected]$domain"
        Subject    = "Update Custom Application files from $computer.$domain"
        SmtpServer = 'SMTP.domain.com'
        Body       = $body
        BodyAsHtml = $true
    }

    Send-MailMessage @mailArgs -Priority High
}

Robocopy switches used:

/MIR     MIRror a directory tree
         equivalent to /E (copy subdirectories, including Empty ones.) plus /PURGE (delete dest files/dirs that no longer exist in source.)
/IS      Includes the same files.
/IT      Includes modified files.
/R:1     number of Retries on failed copies: default 1 million.
/W:1     Wait time between retries: default is 30 seconds.

More switches can be found here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top