当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 Windows Sandbox 做更多事情

作者:精品下载站 日期:2024-12-14 07:59:28 浏览:16 分类:玩电脑

使用 Windows Sandbox 做更多事情


[玩转系统] 使用 Windows Sandbox 做更多事情

我期待更新到 Windows 10 2004 的原因之一是能够访问 Windows Sandbox 功能。我想我对预发布版本进行了修改并且很感兴趣。我通常有一组可以测试的 Hyper-V 虚拟机,但我一直在寻找新的东西来玩。还有什么比沙箱更好玩的呢!

您可以通过“添加/删除程序”启用该功能。这就是我所做的。但您应该能够使用 PowerShell。您可能需要首先验证您是否拥有正确的位。

Get-WindowsOptionalFeature -online -FeatureName Containers-DisposableClientVM

如果是这样,您应该能够启用它。

Enable-WindowsOptionalFeature -Online -FeatureName Containers-DisposableClientVM

安装后,找到“开始”菜单快捷方式并启动它。只需要一会儿。

[玩转系统] 使用 Windows Sandbox 做更多事情

该容器可以访问互联网,并且顾名思义,是一次性的。它也意味着被隔离和保护。但是,您可以自定义 Windows Sandbox 以使其更好地满足您的需求。请注意,您施加的任何配置很可能会降低安全性。或者至少是沙箱的初衷。您必须在安全性和可用性之间取得平衡。

定制文件

Windows Sandbox 没有太多管理界面。也许这会在未来的版本中改变。如果您想要自定义沙盒体验,则需要创建一个使用 .wsb 扩展名的 XML 文件。 https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-sandbox/windows-sandbox-configure-using-wsb-file 有文档,但我将与您分享我的内容我正在做。

<Configuration>
    <MappedFolders>
        <MappedFolder>
        <!-- Create a drive mapping that mirrors my Scripts folder -->
            <HostFolder>C:\scripts</HostFolder>
            <SandboxFolder>C:\scripts</SandboxFolder>
            <ReadOnly>false</ReadOnly>
        </MappedFolder>
         <MappedFolder>
            <HostFolder>C:\Pluralsight</HostFolder>
            <SandboxFolder>C:\Pluralsight</SandboxFolder>
            <ReadOnly>true</ReadOnly>
        </MappedFolder>
    </MappedFolders>
    <ClipboardRedirection>true</ClipboardRedirection>
    <MemoryInMB>8192</MemoryInMB>
    <LogonCommand>
     <Command>C:\scripts\sandbox-setup.cmd</Command>
    </LogonCommand>
</Configuration>

就我的目的而言,我想要一个相对干净的 PowerShell 环境来测试代码和模块。我还想要一些可以在 Pluralsight 课程中使用的东西。

请记住,沙箱中没有任何内容是持久的,但您可以使用配置文件至少设置初始状态。这就是我正在做的事情。该文件的第一部分是将文件夹从我的桌面映射到沙箱。我想要完全访问我的脚本文件夹。为了简单起见,我使用相同的文件夹路径。我还将一个文件夹映射到我的本地 Pluralsight 文件夹。这里有我的设置所需的文件,我稍后会找到这些文件。为了防止做任何愚蠢的事情,我将其设置为只读文件夹。

我希望能够轻松复制和粘贴,因此我启用了剪贴板。我还设置了沙箱使用的内存量。我的台式机内存为 32GB,因此我可以轻松留出 8GB。现在是有趣的部分。

登录命令

您可以定义沙箱启动时运行的命令。经过一些测试和实验后,我得出结论,最简单的解决方案是创建一个批处理 cmd 文件。然后,该文件可以调用我的配置所需的所有其他代码。

REM sandbox-setup.cmd
REM This code runs in the context of the Windows Sandbox
REM Create my standard Work folder
mkdir c:\work

REM set execution policy first so that a setup script can be run
powershell.exe -command "&{Set-ExecutionPolicy RemoteSigned -force}"

REM Now run the true configuration script
powershell.exe -file c:\scripts\sandbox-config.ps1

正如我所提到的,沙箱默认情况下是锁定的,因此我放宽了限制以满足我的需求。比如设置执行策略。主要配置在 Sandox-config.ps1 文件中完成。

Enable-PSRemoting -force -SkipNetworkProfileCheck

Install-PackageProvider -name nuget -force -forcebootstrap -scope allusers
Update-Module PackageManagement,PowerShellGet -force

#run updates and installs in the background
Start-Job {Install-Module PSScriptTools,PSTeachingTools -force}
Start-Job {Install-Module PSReleaseTools -force; Install-PowerShell -mode quiet -enableremoting -EnableContextMenu}
Start-Job {Install-Module WTToolbox -force ; Install-WTRelease}
Start-Job -FilePath c:\scripts\install-vscodesandbox.ps1
Start-Job -FilePath c:\scripts\Set-SandboxDesktop.ps1

#wait for everything to finish
Get-Job | Wait-Job

脚本的第一部分应该是不言而喻的。脚本的最后一部分启动了一系列其他脚本和命令作为后台作业。脚本的结尾是等待所有作业完成,尽管这并没有多大作用,因为所有这些都在“幕后”运行。

我安装了一些标准模块,包括 PSReleaseTools,以便我可以安装 PowerShell 7。我还安装了 WTToolbox 模块,以便可以轻松安装 Windows 终端。当然,我想要 VS Code,以便通过脚本安装。

#Install-VSCodeSandbox.ps1

$file = Join-Path -path $env:temp -child 'VSCodeSetup-x64.exe'
Invoke-WebRequest -Uri "https://update.code.visualstudio.com/latest/win32-x64-user/stable" -OutFile $file -DisableKeepAlive -usebasicparsing

$loadInf = '@
[Setup]
Lang=english
Dir=C:\Program Files\Microsoft VS Code
Group=Visual Studio Code
NoIcons=0
Tasks=desktopicon,addcontextmenufiles,addcontextmenufolders,addtopath
@'

$infPath = Join-Path -path $env:TEMP -child load.inf
$loadInf | Out-File $infPath

Start-Process -FilePath $file -ArgumentList "/VERYSILENT /LOADINF=${infPath}" -Wait

#add extensions
Start-Process -filepath "C:\Program Files\Microsoft VS Code\bin\code.cmd" -ArgumentList "--install-extension ms-vscode.powerShell"

最后一步是配置桌面以满足我的 Pluralsight 需求。这主要是隐藏一些图标(如时钟)和设置壁纸的方法。

# Set-SandboxDesktop.ps1
# my Pluralsight related configuration

function Update-Wallpaper {
  [cmdletbinding(SupportsShouldProcess)]
    Param(
        [Parameter(Position = 0,HelpMessage="The path to the wallpaper file.")]
        [alias("wallpaper")]
        [ValidateScript({Test-Path $_})]
        [string]$Path = $(Get-ItemPropertyValue -path 'hkcu:\Control Panel\Desktop\' -name Wallpaper)
    )

    Add-Type @"

    using System;
    using System.Runtime.InteropServices;
    using Microsoft.Win32;

    namespace Wallpaper
    {
        public class UpdateImage
        {
            [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

            private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);

            public static void Refresh(string path)
            {
                SystemParametersInfo( 20, 0, path, 0x01 | 0x02 );
            }
        }
    }
"@

    if ($PSCmdlet.shouldProcess($path)) {
        [Wallpaper.UpdateImage]::Refresh($Path)
    }
}

#configure the taskbar and hide icons

if (-not (Test-Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer)) {
    [void](New-Item hkcu:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer)
}

Set-ItemProperty hkcu:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\ -Name Hideclock -Value 1
Set-ItemProperty hkcu:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\ -Name HideSCAVolume -Value 1
Set-ItemProperty hkcu:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\ -Name HideSCANetwork -Value 1

if (-not (Test-Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced)) {
    [void](New-Item hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced)
}

Set-ItemProperty hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name HideIcons -Value 1

#configure wallpaper
Set-ItemProperty 'hkcu:\Control Panel\Desktop\' -name Wallpaper -Value C:\Pluralsight\Wallpaper\Pluralsight_Wallpaper_Fall_2015_Black.jpg
Set-ItemProperty 'hkcu:\Control Panel\Desktop\' -name WallpaperOriginX -value 0
Set-ItemProperty 'hkcu:\Control Panel\Desktop\' -name WallpaperOriginY -value 0
Set-ItemProperty 'hkcu:\Control Panel\Desktop\' -name WallpaperStyle -value 10

Update-WallPaper

<# This doesn't work completely in newer versions of Windows 10 Invoke-Command {c:\windows\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters 1,True} #>
#this is a bit harsh but it works
Get-Process explorer | Stop-Process -force    

所有这些是如何结合在一起的?

我的 PowerShell 配置文件中加载了一个函数,可以轻松启动 Windows 沙箱。

Function Start-WindowsSandbox {
    [cmdletbinding(DefaultParameterSetName = "config")]
    [alias("wsb")]
    Param(
        [Parameter(ParameterSetName = "config")]
        [ValidateScript({Test-Path $_})]
        [string]$Configuration = "C:\scripts\WinSandBx.wsb",
        [Parameter(ParameterSetName = "normal")]
        [switch]$NoSetup
    )

    Write-Verbose "Starting $($myinvocation.mycommand)"

    if ($NoSetup) {
        Write-Verbose "Launching default WindowsSandbox.exe"
        c:\windows\system32\WindowsSandbox.exe
    }
    else {
        Write-Verbose "Launching WindowsSandbox using configuration file $Configuration"
        Invoke-Item $Configuration
    }

    Write-Verbose "Ending $($myinvocation.mycommand)"
}    

默认行为是使用我的自定义文件。尽管我给了自己一个选项来启动沙箱而不进行任何自定义。该函数有一个别名 wsb,这使得它非常容易运行。

当我运行它时,我得到带有默认桌面的 Windows Sandbox。我的安装程序和配置文件正在后台运行。大约一分钟之内,桌面就会变成我的 Pluralsight 背景,我知道我快完成了。我可能会尝试添加 BurntToast 通知。

[玩转系统] 使用 Windows Sandbox 做更多事情

但现在我已经有了一个可以满足我的要求的沙箱配置。是的,我降低了整体安全性,但这并不是我不能忍受的。

欢迎您获取代码并亲自尝试。一如既往,我很想听听你的想法。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯