Search code examples
powershelldsc

Cannot create a folder on the partition that was just created within a DSC script


I'm trying to use DSC to format drives and create a certain folder structure on newly formatted drives.

Right after I've created a partition, formatted a disk and gave it a drive letter I'm trying to create a folder using the new disk path however I'm receiving Cannot find drive. A drive with the name 'K' does not exist types of errors on New-Item call. This code is an example of one executed within a Script DSC:

$someDiskNumber = 3 # for the sake of testing

Initialize-Disk -Number $someDiskNumber -PartitionStyle GPT -PassThru
$partition = New-Partition -DiskNumber $someDiskNumber -UseMaximumSize -DriveLetter 'K'
Format-Volume -Partition $partition -FileSystem NTFS -AllocationUnitSize 65536 -NewFileSystemLabel "san-root" -Confirm:$False
New-Item -Path "K:\Test" -ItemType Directory -Force -ErrorAction Stop

How do I make the DSC script "rediscover" the new volume to allow running New-Item for it?

What I have tried (no success):

  • Running Update-Disk -DiskNumber $someDiskNumber after the Format-Volume call
  • Running Update-HostStorageCache after the Format-Volume call
  • Add a while loop after the Format-Volume call to wait for Test-Path "K:\" to return True (it looped forever)

P.S. I am aware of the xStorage DSC module but unfortunately I cannot use it due to limitations (irrelevant to the question).


Solution

  • Figured an answer five minutes after trying StackOverflow. Adding the command below will force PowerShell to refresh the cache and get the missing drives.

    $null = Get-PSDrive