簡體   English   中英

Set-RunOnce從更改usb驅動器號運行ps1文件

[英]Set-RunOnce run ps1 file from changing usb drive letter

所以我使用的是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 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'

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM