How do I run a PowerShell script when the computer starts?

前端 未结 15 1144
-上瘾入骨i
-上瘾入骨i 2020-11-30 19:24

I have a PowerShell script that monitors an image folder. I need to find a way to automatically run this script after the computer starts.

I already tried the follow

相关标签:
15条回答
  • 2020-11-30 19:54

    Prerequisite:

    1. Start powershell with the "Run as Administrator" option

    2. Enable running unsigned scripts with:

    set-executionpolicy remotesigned
    

    3. prepare your powershell script and know its path:

    $path = "C:\Users\myname\myscript.ps1"
    

    Steps:

    1. setup a trigger, see also New-JobTrigger (PSScheduledJob) - PowerShell | Microsoft Docs

    $trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30
    

    2. register a scheduled job, see also Register-ScheduledJob (PSScheduledJob) - PowerShell | Microsoft Docs

    Register-ScheduledJob -Trigger $trigger -FilePath $path -Name MyScheduledJob
    

    you can check it with Get-ScheduledJob -Name MyScheduledJob

    3. Reboot Windows (restart /r) and check the result with:

    Get-Job -name MyScheduledJob
    

    see also Get-Job (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs

    References:

    1. How to enable execution of PowerShell scripts? - Super User
    2. Use PowerShell to Create Job that Runs at Startup | Scripting Blog
    0 讨论(0)
  • 2020-11-30 19:56

    A relatively short path to specifying a Powershell script to execute at startup in Windows could be:

    1. Click the Windows-button (Windows-button + r)
    2. Enter this:

    shell:startup

    1. Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut

    2. Create a shortcut to your script, e.g:

    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "C:\Users\someuser\Documents\WindowsPowerShell\Scripts\somesscript.ps1"

    Note the use of -NoProfile In case you put a lot of initializing in your $profile file, it is inefficient to load this up to just run a Powershell script. The -NoProfile will skip loading your profile file and is smart to specify, if it is not necessary to run it before the Powershell script is to be executed.

    Here you see such a shortcut created (.lnk file with a Powershell icon with shortcut glyph):

    0 讨论(0)
  • 2020-11-30 19:57

    What I do is create a shortcut that I place in shell:startup.

    The shortcut has the following:

    Target: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "C:\scripts\script.ps1"

    (replacing scripts\scripts.ps1 with what you need)

    Start In: C:\scripts

    (replacing scripts with folder which has your script)

    0 讨论(0)
提交回复
热议问题