1 [CmdletBinding()]
2 param(
3     [Parameter(Mandatory=$true,
4     HelpMessage="Drive letter to use for the RAMDisk")]
5     [String]$drive,
6     [Parameter(HelpMessage="Size to allocate to the RAMDisk")]
7     [UInt64]$size=1GB
8 )
9 
10 $ErrorActionPreference = "Stop"
11 Set-StrictMode -Version Latest
12 
13 Write-Output "Installing FS-iSCSITarget-Server"
14 Install-WindowsFeature -Name FS-iSCSITarget-Server
15 
16 Write-Output "Starting MSiSCSI"
17 Start-Service MSiSCSI
18 $retry = 10
19 do {
20     $service = Get-Service MSiSCSI
21     if ($service.Status -eq "Running") {
22         break;
23     }
24     $retry--
25     Start-Sleep -Milliseconds 500
26 } until ($retry -eq 0)
27 
28 $service = Get-Service MSiSCSI
29 if ($service.Status -ne "Running") {
30     throw "MSiSCSI is not running"
31 }
32 
33 Write-Output "Configuring Firewall"
34 Get-NetFirewallServiceFilter -Service MSiSCSI | Enable-NetFirewallRule
35 
36 Write-Output "Configuring RAMDisk"
37 # Must use external-facing IP address, otherwise New-IscsiTargetPortal is
38 # unable to connect.
39 $ip = (
40     Get-NetIPAddress -AddressFamily IPv4 |
41     Where-Object {$_.IPAddress -ne "127.0.0.1"}
42 )[0].IPAddress
43 if (
44     -not (Get-IscsiServerTarget -ComputerName localhost | Where-Object {$_.TargetName -eq "ramdisks"})
45 ) {
46     New-IscsiServerTarget `
47         -ComputerName localhost `
48         -TargetName ramdisks `
49         -InitiatorId IPAddress:$ip
50 }
51 
52 $newVirtualDisk = New-IscsiVirtualDisk `
53     -ComputerName localhost `
54     -Path ramdisk:local$drive.vhdx `
55     -Size $size
56 Add-IscsiVirtualDiskTargetMapping `
57     -ComputerName localhost `
58     -TargetName ramdisks `
59     -Path ramdisk:local$drive.vhdx
60 
61 Write-Output "Connecting to iSCSI"
62 New-IscsiTargetPortal -TargetPortalAddress $ip
63 Get-IscsiTarget | Where-Object {!$_.IsConnected} | Connect-IscsiTarget
64 
65 Write-Output "Configuring disk"
66 $newDisk = Get-IscsiConnection |
67     Get-Disk |
68     Where-Object {$_.SerialNumber -eq $newVirtualDisk.SerialNumber}
69 
70 Set-Disk -InputObject $newDisk -IsOffline $false
71 Initialize-Disk -InputObject $newDisk -PartitionStyle MBR
72 New-Partition -InputObject $newDisk -UseMaximumSize -DriveLetter $drive
73 
74 Format-Volume -DriveLetter $drive -NewFileSystemLabel Temp -FileSystem NTFS
75