#Function to get mounted VHD drive letters. Thanks internet for the example.
function get-mountedvhdDrive {
$disks = Get-CimInstance -ClassName Win32_DiskDrive | where Caption -eq "Microsoft Virtual Disk"
foreach ($disk in $disks){
$vols = Get-CimAssociatedInstance -CimInstance $disk -ResultClassName Win32_DiskPartition
foreach ($vol in $vols){
Get-CimAssociatedInstance -CimInstance $vol -ResultClassName Win32_LogicalDisk |
where VolumeName -ne 'System Reserved'
}
}
}
#Get just the drive letters (Used to ensure only one device)
$vhdletter = (get-mountedvhdDrive | select DeviceID )
#Present Results
clear
""
echo "The following VHDs are attached to the system:"
get-mountedvhdDrive
""
#Ensure there is only one VHD atached - (Saftey measure)
if ($vhdletter.length -gt 1) {Write-Host "Cannot Automatically Assign IP Address - Multiple VHDs attached. Sorry but I cannot help you anymore." -foregroundcolor red; Write-Host ""; break}
else {Write-Host "Only one VHD attached - Nice and safe. Moving on." -foregroundcolor green}
#Lock file used globally
$lockfile = "C:\lock.txt"
#Function to check if lockfile is locked.
function waitForIt
{
""
#If lock file does not already exist, create. Wait just in case another script is running.
Start-Sleep -m (Get-Random -minimum 1500 -maximum 4000)
If (!(Test-Path $lockfile -PathType Leaf))
{
Write-Host "Lock File Does not Exist, Creating"
New-Item $lockfile -type file
#Set to 0 to allow script to continue
echo 0 >>$lockfile
}
#Continue if lock file exists
ElseIf (Test-Path $lockfile -PathType Leaf)
{
#Echo "Please Wait" until lock file returns 0 (Free)
$busy = (Get-Content $lockfile)[0]
$crazy = (Get-Random -minimum 10000 -maximum 50000)
Write-Host "Please Wait";
Write-Host "";
do {Write-Host $crazy" bananas remaining." -foregroundcolor yellow; $crazy = ($crazy - 500); Write-Host ""; $busy = (Get-Content $lockfile); Start-Sleep -m 1000}
while ($busy -ne 0)
}
}
""
#Added step for additional randomness.
Read-Host "Enter to Continue"
function copyToVhd
#This will lock the lockfile, mount the VHD, copy a file into the VHD, unmount the VHD and then unlock the lock file.
{
waitForIt
#Clear lockfile as we are only checking the first 'item' in the array.
Clear-Content $lockfile
#Lock the lockfile
echo 1 >>$lockfile
#Script to copy to VHD ETC coming soon. Sample echo for now.
echo "Copying to VHD"
""
Read-Host "Enter to Continue"
echo "Copy complete"
#After script complete, unlock lock file
#Clear lockfile
Clear-Content $lockfile
echo 0 >>$lockfile
}
copyToVhd