I'm writing a simple powershell script that would automate offsite backup from Windows file server to another remote Windows server. Files might be in use, so in order for Robocopy to sucessfully copy them I need to copy the files from last available Volume Shadow Copy for that specific drive.
I can find the last Shadow Copy with Powershell just fine; the problem is that I cannot actually "referece" it (mount it) in order to access files on the Shadow Copy.
But this "magically" changes if I first access contents of the Shadow Copy via Windows Explorer GUI
Then all of the sudden, I can access the Shadow Copy just fine and copy the contents to a remote backup server.
Here's the code in question:
#Find the latest Shadow copy
$HDDriveID = (Get-WmiObject win32_volume -filter "DriveLetter='E:'").DeviceID
$LastShadowCopy = Get-WmiObject win32_shadowcopy | Where-Object {$_.VolumeName -eq $HDDriveID} | Sort-Object InstallDate | Select-Object -Last 1
# And parse the path so that we can mount it
$arr = $LastShadowCopy.InstallDate.Split('+').Split('.')
$VolumeShadowCopytime = [DateTime]::ParseExact($arr[0], 'yyyyMMddHHmmss', $null)
$UTCTime = $VolumeShadowCopytime.AddHours(-[int]$arr[2]/60)
$VolumeShadowCopyPath = "\\127.0.0.1\E$\@GMT-" + (Get-Date $UTCTime).ToString("yyyy.MM.dd-HH.mm.ss") + "\"
# Then, let's actually mount it:
New-PSDrive -Name Y -PSProvider FileSystem -Root $VolumeShadowCopyPath
If I run this part of a script without accessing the last Shadow Copy via GUI, I receive the following error:
New-PSDrive : The specified drive root "\\127.0.0.1\E$\@GMT-2018.06.27-05.00.09\" either does not exist, or it is not a folder.
At [scriptlocation]\BackupToAzureDrive.ps1:21 char:1
+ New-PSDrive -Name Y -PSProvider FileSystem -Root $VolumeShadowCopyPat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (Y:PSDriveInfo) [New-PSDrive], IOException
+ FullyQualifiedErrorId : DriveRootError,Microsoft.PowerShell.Commands.NewPSDriveCommand
Again, as soon as the Shadow copy is (aparently?) properly referenced by Windows when I open it via Windows Explorer, I get no such error. Shadow Copy gets mounted without any problems and I can access files&folders.
I'm no Powershell guru nor am I very enthusiastic about it. I'm stuck with this problem for days now. Does anyone have an idea how to solve this and/or knows of the workaround?