Fun With Windows Sandbox

I managed to solve a problem using Windows Sandbox a while back, and I thought I should blog about it.

The basic problem was this: I needed to run a PowerShell script that relied on a specific combination of old modules. It had to be run in the old Windows PowerShell, not PowerShell 7. I had originally hoped that I could find some way to set up a PowerShell sandbox of sorts, but there didn’t seem to be an obvious way to do that. So then I started looking into Windows Sandbox.

We start with a .wsb file that defines the sandbox. Mine looks like this:

<Configuration>
  <Networking>Enable</Networking>
  <MappedFolders>
    <MappedFolder>
      <HostFolder>\\my-pc\c$\dev\Projects\myproject</HostFolder>
      <SandboxFolder>C:\myproject</SandboxFolder>
      <ReadOnly>false</ReadOnly>
    </MappedFolder>
  </MappedFolders>
  <LogonCommand>
    <Command>c:\myproject\myfolder\sb-start.cmd</Command>
  </LogonCommand>
</Configuration>

This maps \\my-pc\c$\dev\Projects\myproject from my dev VM to C:\myproject in the sandbox.
And it runs c:\myproject\myfolder\sb-start.cmd once the sandbox starts.
I had a little trouble getting all of this right. I really wanted to have the logon command set up the PowerShell environment fully, and maybe even run my script, but that didn’t work.
So the startup command file just has this:

cd C:\myproject\myfolder
explorer.exe .
powershell.exe -executionpolicy unrestricted -command "start powershell {-noexit}"

So it starts Explorer and PowerShell, pointing at my work folder. Good enough.
Then, I manually run a script I call sandbox-setup.ps1, which looks a bit like this:

Write-Warning "This script installs the modules needed for the weird old script." -WarningAction Inquire
Set-ExecutionPolicy RemoteSigned -Force
Install-PackageProvider -Name NuGet -Force
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module -Name WeirdModule -AllowClobber -Scope CurrentUser
Install-Module -Name Az.Accounts -RequiredVersion 2.9.1
Install-Module -Name Az.KeyVault -RequiredVersion 4.6.1

And then I can run the actual script. It produces a .CSV file, which is written to the mapped drive, so I can shut down the sandbox after running the script.

On the one hand, this feels like a kludgey way of doing this. On the other hand, it’s the simplest way I could think of. For more info on running PowerShell scripts in Windows Sandbox, see here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.