I have recently setup a virtual machine on a local computer which I need to backup to the onedrive folder on it each week. I put together the following PowerShell script to try and shut the vm down then use 7zip to do the compress and saving
# Created 7-2-2024 for backing up VHDX files for NAGC
#Variable Declarations
$SourcePath = "C:ProgramDataMicrosoftWindowsVirtual Hard DisksAccounting.vhdx"
$DestinationPath = "C:UsersthisiOneDrive - Default DirectoryDocuments"
$ZipDestinationPath = "C:UsersthisiOneDrive - Default DirectoryDocumentsAccounting $(get-date -f yyyy-MM-dd).zip"
$BackupCount = 3
$files = Get-ChildItem -Path $DestinationPath -filter "*.vhdx" | Sort-Object -property LastWriteTime -Descending
#Stop VM
Stop-VM -Name Accounting -TurnOff
$VM = Get-VM -Name Accounting
#if give vm time to shut down
while ($VM.State -ne "off")
{
start-sleep -s 5
}
#ensure vm is off before completing operation
if($VM.State -eq "off")
{
#compress file
$7zipPath = "$env:ProgramFiles7-Zip7z.exe"
if (-not (Test-Path -Path $7zipPath -PathType Leaf)) {
throw "7 zip executable '$7zipPath' not found"
}
Set-Alias Start-SevenZip $7zipPath
Start-SevenZip a -mx=9 $ZipDestinationPath $SourcePath
#start vm again
Start-VM -Name Accounting
if ($files.Count -gt $BackupCount) {
# Select the files to delete
$filesToDelete = $files | select -Skip $BackupCount
#delete the selected files, confirm this is correct then remove the
$filesToDelete | Remove-Item -Force -Confirm:$false
}
}
Whenever it gets to the compressing and saving I draw the following issue:
7-Zip 24.07 (x64) : Copyright (c) 1999-2024 Igor Pavlov : 2024-06-19
Scanning the drive:
1 file, 168423325696 bytes (157 GiB)
Creating archive: C:UsersthisiOneDrive - Default DirectoryDocumentsNAGCAccounting 2024-07-08.zip
Add new data to archive: 1 file, 168423325696 bytes (157 GiB)
Error:
cannot open file
C:UsersthisiOneDrive - Default DirectoryDocumentsNAGCAccounting 2024-07-08.zip
The system cannot find the file specified.
System ERROR:
The system cannot find the file specified.
I am very new to powershell scripting so any improvements you see as well as fixing this error would be helpful.
Thanks!!