2025年10月19日

Create a Virtual Disk in a Ramdisk, mounting it at boot and set it as TEMP environment variable in Windows

step 1. Install Imdisk toolkit and initiate a ramdisk at R: with it.

step 2. Create a powershell script with codes shown as below:

function Set_env_temp_folder_path {
    param (
        [string]$FolderPath
    )
    [Environment]::SetEnvironmentVariable("TEMP", $FolderPath, "User")
    [Environment]::SetEnvironmentVariable("TMP", $FolderPath, "User")
    [Environment]::SetEnvironmentVariable("TEMP", $FolderPath, "Machine")
    [Environment]::SetEnvironmentVariable("TMP", $FolderPath, "Machine")
}
$RTmpFolderPath = "R:\RTemp"
New-Item -Path $RTmpFolderPath -ItemType Directory
Set_env_temp_folder_path $RTmpFolderPath

function Remove-FolderIfExists {
    param (
        [string]$FolderPath
    )

    if (Test-Path -Path $FolderPath -PathType Container) {
        try {
            Remove-Item -Path $FolderPath -Recurse -Force
            Write-Host "Folder '$FolderPath' has been deleted successfully."
        } catch {
            Write-Error "Failed to delete folder '$FolderPath'. Error: $_"
        }
    } else {
        Write-Host "Folder '$FolderPath' does not exist."
    }
}

$VhdPath = "R:\ramdisk.vhdx"
$TmpFolderPath = "R:\Temp"
Remove-FolderIfExists $TmpFolderPath
$TmpFolderTargetPath = "S:\Temp"

$break_while_loop = $false
while ($break_while_loop -ne $true) {
    try {
        New-VHD -Path $VhdPath -SizeBytes 22GB -Dynamic
        Mount-VHD -Path $VhdPath
        $disk = Get-DiskImage -ImagePath $VhdPath | Get-Disk
        Initialize-Disk -Number $disk.Number -PartitionStyle GPT -PassThru | New-Partition -UseMaximumSize -DriveLetter S | Format-Volume -Compress -FileSystem NTFS -NewFileSystemLabel "SecRamDisk" -Confirm:$false
        New-Item -Path $TmpFolderTargetPath -ItemType Directory
        Set_env_temp_folder_path $RTmpFolderPath
        Remove-FolderIfExists $TmpFolderPath
        cmd /c mklink /D "$TmpFolderPath" "$TmpFolderTargetPath"
        Set_env_temp_folder_path $TmpFolderPath
        $break_while_loop = $true
    } catch {
        Write-Host "Error mounting VHD: $_"
        $break_while_loop = $fa
    }
}

step 3. Execute Windows Task Scheduler(工作排程器) and create a new task to run at boot:

command:

powershell

parameter:
-ExecutionPolicy Bypass -NoExit "D:\Ramdisk\RamdiskStartupConfigure\attachRamdisk.ps1

Some troubles in installing programs with Imdisk as source of ramdisk can be avoided with this method.

0 comment(s):

張貼留言