0

所以我正在使用这个 Powershell 脚本:Set-RunOnce https://www.powershellgallery.com/packages/WindowsImageConverter/1.0/Content/Set-RunOnce.ps1

当我将驱动器号硬编码到 (E:\ServerInstall.ps1) 中时,它就像一个魅力。但我想确保这个脚本可以从 USB 插入的任何驱动器号运行

如何在注册表中获取此更改的驱动器号?

我首先尝试使用-ExecutionPolicy Bypass,但这也没有太大变化。

我也试过这个:

$getusb = Get-WmiObject Win32_Volume -Filter "DriveType='2'" 。.\Set-RunOnce.ps1 设置-RunOnce -Command

'%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe `-ExecutionPolicy Unrestricted -File $getusb.Name\ServerInstall.ps1'

--> $getusb.Name\ServerInstall.ps1 最终在注册表中被硬编码,但它不知道 $getusb.name 是什么,所以脚本没有启动。

. .\Set-RunOnce.ps1
Set-RunOnce -Command '%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe `
-ExecutionPolicy Unrestricted -File (wmic logicaldisk where drivetype=2)
ServerInstall.ps1'
4

1 回答 1

0

Set-RunOnce函数非常容易理解和调整。
我建议创建一个你自己的派生函数来做你想做的事情并使用它来代替:

function Set-RunOnceForUSB {
    # get the driveletter from WMI for the first (possibly only) USB disk
    $firstUSB   = @(Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DriveType -eq 2} | Select-Object -ExpandProperty DeviceID)[0]
    # or use:
    # $firstUSB = @(Get-WmiObject Win32_Volume -Filter "DriveType='2'" | Select-Object -ExpandProperty DriveLetter)[0]

    # combine that with the name of your script file to create a complete path
    $scriptPath = Join-Path -Path $firstUSB -ChildPath 'ServerInstall.ps1'

    # create the command string. use double-quotes so the variable $scriptPath gets expanded
    $command = "%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File $scriptPath"

    # next, add this to the registry same as the original Set-RunOnce function does
    if (-not ((Get-Item -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce).Run )) {
        New-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $command -PropertyType ExpandString
    }
    else {
        Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'Run' -Value $command -PropertyType ExpandString
    }
}
于 2019-05-28T18:57:53.930 回答