简体   繁体   中英

Set-RunOnce run ps1 file from changing usb drive letter

So I am using this Powershell script: Set-RunOnce https://www.powershellgallery.com/packages/WindowsImageConverter/1.0/Content/Set-RunOnce.ps1

When I put the driveletter hardcoded in (E:\\ServerInstall.ps1) it works like a charm. But I want to be sure this script can run from any drive letter the USB gets plugged into .

How can I get this changing drive letter in the registry?

I first tried it with -ExecutionPolicy Bypass , but that didn't change much either.

I also tried this:

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

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

--> $getusb.Name\\ServerInstall.ps1 ended being hardcoded in the registry, but it didn't know what $getusb.name was, so the script didn't launch.

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

The Set-RunOnce function is really easy to understand and simple to adjust.
I would suggest creating a derived function of your own to do what you want and use that instead:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM