Set-RunOnce从更改USB驱动器号运行ps1文件

时间:2019-05-28 14:39:01

标签: powershell cmd automation runonce

所以我正在使用以下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 Set-RunOnce -Command

     

'%systemroot%\ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe`   -ExecutionPolicy不受限制-文件$ 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'

1 个答案:

答案 0 :(得分: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
    }
}