On previous versions of Windows I have used the below technique to run a batch file on Windows startup.
- Create a shortcut to the batch file.
- Once the shortcut is created, right-click the shortcut file and select Cut.
- Click Start, then Programs or All Programs. Find the Startup folder and right-click that folder, then select Open.
- Once the Startup folder is opened, click Edit in the menu bar, then Paste to paste the shortcut file into the Startup folder. If you do not see the menu bar, press the Alt key to make the menu bar visible.
Any shortcuts in the Startup folder will automatically run each time the user logs in to Windows.
I have been unsuccessful in finding how to do something similar on Windows 10.
Any ideas?
asked Aug 10, 2015 at 20:20
baynezybaynezy
1,3712 gold badges10 silver badges9 bronze badges
2
The startup folder is still there and functions as normal.
To access it, press Windows+R, then type shell:startup
.
You should be able to do what you were previously doing in Windows 7 from there.
answered Aug 10, 2015 at 20:43
7
You can use scheduled tasks and set it to run at startup.
Go to Manage → Scheduled Tasks → Create a Basic Task.
Once at the dialog box, set a name, click Next and select at startup, Next again and select the program you want to run and next to finish. Done!
answered Aug 10, 2015 at 20:59
sarakustasarakusta
5133 silver badges4 bronze badges
1
To add to user314352’s answer:
The startup folder is still there and functions as normal.
To access it, press Windows+R, then type shell:startup.
You should be able to do what you were previously doing in Windows 7 from there.
You can also type shell:common startup
to access the startup folder for all users.
answered Dec 26, 2020 at 11:05
Azeezah MAzeezah M
1011 silver badge2 bronze badges
If you don’t have access to Windows+X functionality, you can navigate manually to the two startup folders:
- User:
C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
- All users:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
Here’s a useful batch file to open either or both of these folders:
rem Load the current user Start folder
%SystemRoot%\explorer.exe "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup"
rem Load the "All Users" Start folder
%SystemRoot%\explorer.exe "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp"
Note: Above applies to Windows 8.1 and Windows 10 (and maybe earlier versions).
answered Jan 20, 2020 at 13:00
AlainDAlainD
4,48715 gold badges50 silver badges96 bronze badges
3
I have an MSI motherboard that is not playing nice with my beloved Gateway Anykey keyboard. Num Lock won’t turn off at boot.
I added a «NumLock Off» utility to the shell:startup
folder. No help. I added it to Scheduled Tasks and that worked. BTW, I couldn’t schedule a shortcut to the utility. I could only schedule a batch file with the numlock.exe file and the «off» parameter on the command line.
answered Nov 20, 2016 at 3:40
1
Alternative through Group Policy
gpedit
: Local Computer Policy > Computer Configuration > Windows Settings > Script (Startup/Shutdown)
answered Jun 2, 2021 at 9:04
user.dzuser.dz
6687 silver badges19 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
On previous versions of Windows I have used the below technique to run a batch file on Windows startup.
- Create a shortcut to the batch file.
- Once the shortcut is created, right-click the shortcut file and select Cut.
- Click Start, then Programs or All Programs. Find the Startup folder and right-click that folder, then select Open.
- Once the Startup folder is opened, click Edit in the menu bar, then Paste to paste the shortcut file into the Startup folder. If you do not see the menu bar, press the Alt key to make the menu bar visible.
Any shortcuts in the Startup folder will automatically run each time the user logs in to Windows.
I have been unsuccessful in finding how to do something similar on Windows 10.
Any ideas?
asked Aug 10, 2015 at 20:20
baynezybaynezy
1,3712 gold badges10 silver badges9 bronze badges
2
The startup folder is still there and functions as normal.
To access it, press Windows+R, then type shell:startup
.
You should be able to do what you were previously doing in Windows 7 from there.
answered Aug 10, 2015 at 20:43
7
You can use scheduled tasks and set it to run at startup.
Go to Manage → Scheduled Tasks → Create a Basic Task.
Once at the dialog box, set a name, click Next and select at startup, Next again and select the program you want to run and next to finish. Done!
answered Aug 10, 2015 at 20:59
sarakustasarakusta
5133 silver badges4 bronze badges
1
To add to user314352’s answer:
The startup folder is still there and functions as normal.
To access it, press Windows+R, then type shell:startup.
You should be able to do what you were previously doing in Windows 7 from there.
You can also type shell:common startup
to access the startup folder for all users.
answered Dec 26, 2020 at 11:05
Azeezah MAzeezah M
1011 silver badge2 bronze badges
If you don’t have access to Windows+X functionality, you can navigate manually to the two startup folders:
- User:
C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
- All users:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
Here’s a useful batch file to open either or both of these folders:
rem Load the current user Start folder
%SystemRoot%\explorer.exe "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup"
rem Load the "All Users" Start folder
%SystemRoot%\explorer.exe "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp"
Note: Above applies to Windows 8.1 and Windows 10 (and maybe earlier versions).
answered Jan 20, 2020 at 13:00
AlainDAlainD
4,48715 gold badges50 silver badges96 bronze badges
3
I have an MSI motherboard that is not playing nice with my beloved Gateway Anykey keyboard. Num Lock won’t turn off at boot.
I added a «NumLock Off» utility to the shell:startup
folder. No help. I added it to Scheduled Tasks and that worked. BTW, I couldn’t schedule a shortcut to the utility. I could only schedule a batch file with the numlock.exe file and the «off» parameter on the command line.
answered Nov 20, 2016 at 3:40
1
Alternative through Group Policy
gpedit
: Local Computer Policy > Computer Configuration > Windows Settings > Script (Startup/Shutdown)
answered Jun 2, 2021 at 9:04
user.dzuser.dz
6687 silver badges19 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
Как оказалось задачка из заголовка не так то просто реализуется. Вроде было бы логично если бы программы из HKLM:\Software\Microsoft\Windows\CurrentVersion\Run или RunOnce запускались бы при включении компьютера, ан нет — они стартуют при входе под учетной записью с административными полномочиями. Так что приходится искать другие пути.
Например стартап скрипт из групповых/локальных политик. Этот метод работает, но к сожалению сложновато создать политику из скрипта. Даже локальная политика состоит из немалого количества ключей, создавать которые с помощью reg.exe замучаешься, а импортировать — это уже отдельный .reg файл, что IMHO не слишком красиво ради такой простой (казалось бы) задачки…
В итоге из более менее «красивых» способов нашел только использование планировщика заданий. С помощью утилиты schtasks.exe (доступна на xp/2k3 и выше) добавить задачу, и указать выполнение при загрузке системы. Ну и до кучи я использовал учетную запись System (так как мне был необходим доступ на сетевые ресурсы, а соответственно программа должна использовать учетную запись компьютера из AD).
schtasks /create /ru SYSTEM /sc ONSTART /tn SetupDM /tr "c:\SetupDM.cmd"
Эту строчку уже не стыдно использовать в скрипте. Ну и если достаточно выполнить задачу однократно, то можно после запуска удалить её:
schtasks /delete /f /tn SetupDm
Первый способ
Для того чтобы добавить скрипт в автозагрузку в Windows 10 необходимо:
1) Сделать ярлык к файлу скрипту
2) В проводнике прописать shell:startup и добавить в этой папке ярлык нашего скрипта на автозапуск.
3) Смотрим в автозапуске, есть ли наш скрипт там или нет.
4) Перезагружаемся и проверяем работу.
Второй способ
Если для запуска скрипта требуется права администратора, то необходимо сделать автозапуск через планировщик задач:
1) через поиск открывает планировщик задач
2) создаем новую простую задачу
3) называем задачу и в траггере ставим «При входе в Windows»:
4) отмечаем, что запуск программы:
5) выбираем программу:
6) завершаем создание задачи
7) правой кнопкой мыши кликаем по задаче и выбираем свойства. Во вкладке «Общее» ставим галочку «Выполнить с наивысшими правами» и применяем изменения
перезагружаем компьютер и проверяем работу скрипта.
Категории: Windows
Метки: windows
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 following methods, but I couldn’t get it working.
-
Use
msconfig
and add the PowerShell script to startup, but I cannot find the PowerShell script on that list. -
Create a shortcut and drop it to startup folder. No luck.
%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -File "C:\Doc\Files\FileMonitor.ps1"
or
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -File "C:\Doc\Files\FileMonitor.ps1"
Here’s my PowerShell script:
$folder = "C:\\Doc\\Files" $dest = "C:\\Doc\\Files\\images" $filter = "*.jpg" $fsw = new-object System.IO.FileSystemWatcher $folder, $filter -Property @{ IncludeSubDirectories=$false NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite' } $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { Start-Sleep -s 10 Move-Item -Path C:\Doc\Files\*.jpg C:\Doc\Files\images }
-
I also tried to add a basic task using
taskschd.msc
. It is still not working.Here’s what I found, and maybe that will help to debug it.
If I open up a PowerShell window and run the script there, it works. But if I run it in a command prompt,
powershell.exe -File "C:\Doc\Files\FileMonitor.ps1"
It will not work. I am not sure it’s a permission problem or something else.
BTW, I have PowerShell 3.0 installed, and if I type $host.version, it will show 3 there. But my powershell.exe seems like it is still v1.0.
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
asked Dec 13, 2013 at 20:17
qinking126qinking126
11.4k25 gold badges74 silver badges124 bronze badges
4
I finally got my PowerShell script to run automatically on every startup. You will need to create two files: the first is the Powershell script (e.g. script.ps1
) and the second is a .cmd file that will contain commands that will run on the command prompt (e.g. startup.cmd
).
The second file is what needs to be executed when the computer starts up, and simply copy-pasting the .ps1 to the startup folder won’t work, because that doesn’t actually execute the script — it only opens the file with Notepad. You need to execute the .cmd which itself will execute the .ps1 using PowerShell. Ok, enough babbling and on to the steps:
- Create your .ps1 script and place it in a folder. I put it on my desktop for simplicity. The path would look something like this:
%USERPROFILE%\Desktop\script.ps1
- Create a .cmd file and place it in
%AppData%\Microsoft\Windows\Start Menu\Programs\Startup\startup.cmd
Doing this will execute the cmd file every time on startup. Here is a link of how to create a .cmd file if you need help.
- Open the .cmd file with a text editor and enter the following lines:
PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "%TEMP%\StartupLog.txt" 2>&1
PowerShell %USERPROFILE%\Desktop\script.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
This will do two things:
- Set the Execution Policy of your PowerShell to Unrestricted. This is needed to run scripts or else PowerShell will not do it.
- Use PowerShell to execute the .ps1 script found in the path specified.
This code is specifically for PowerShell v1.0. If you’re running PowerShell v2.0 it might be a little different. In any case, check this source for the .cmd code.
- Save the .cmd file
Now that you have your .ps1 and .cmd files in their respective paths and with the script for each, you are all set.
DrumRobot
3931 gold badge3 silver badges15 bronze badges
answered Aug 24, 2015 at 18:41
7
You could set it up as a Scheduled Task, and set the Task Trigger for «At Startup»
answered Dec 13, 2013 at 20:22
mjolinormjolinor
66.3k7 gold badges114 silver badges135 bronze badges
5
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)
answered Dec 31, 2016 at 6:24
haboutnnahhaboutnnah
1,11811 silver badges19 bronze badges
6
You could create a Scheduler Task that runs automatically on the start, even when the user is not logged in:
schtasks /create /tn "FileMonitor" /sc onstart /delay 0000:30 /rl highest /ru system /tr "powershell.exe -file C:\Doc\Files\FileMonitor.ps1"
Run this command once from a PowerShell as Admin and it will create a schedule task for you. You can list the task like this:
schtasks /Query /TN "FileMonitor" /V /FO List
or delete it
schtasks /Delete /TN "FileMonitor"
answered Jun 15, 2019 at 21:50
hirschnasehirschnase
1111 silver badge2 bronze badges
1
This is really just an expansion on @mjolinor simple answer [Use Task Scheduler].
I knew «Task Scheduler» was the correct way, but it took a bit of effort to get it running the way I wanted and thought I’d post my finding for others.
Issues including:
- Redirecting output to logs
- Hiding the PowerShell window
Note: You must have permission to run script see ExecutionPolicy
Then in Task Scheduler, the most important/tricky part is the Action
It should be Start a Program
Program/Script:
powershell
Add arguments (optional) :
-windowstyle hidden -command full\path\script.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
Note:
If you see -File
on the internet, it will work, but understand nothing can be after -File
except the File Path, IE: The redirect is taken to be part of the file path and it fails, you must use -command
in conjunction with redirect, but you can prepend additional commands/arguments such as -windowstyle hidden
to not show PowerShell window.
I had to adjust all Write-Host
to Write-Output
in my script as well.
answered Sep 28, 2020 at 5:11
Try this: create a shortcut in startup folder and input
PowerShell "& 'PathToFile\script.ps1'"
This is the easiest way.
gkubed
1,8593 gold badges33 silver badges45 bronze badges
answered Mar 25, 2020 at 14:59
2
Copy ps1 into this folder, and create it if necessary. It will run at every start-up (before user logon occurs).
C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
Also it can be done through GPEDIT.msc if available on your OS build (lower level OS maybe not).
answered Dec 15, 2013 at 13:05
Knuckle-DraggerKnuckle-Dragger
6,6744 gold badges26 silver badges41 bronze badges
1
Be sure, whenever you want PowerShell to run automatically / in the background / non-interactive, it’s a good idea to specify the parameters
-ExecutionPolicy Bypass
to PowerShell.exe
PowerShell.exe -ExecutionPolicy Bypass
answered Jun 16, 2019 at 1:33
I have a script that starts a file system watcher as well, but once the script window is closed the watcher dies. It will run all day if I start it from a powershell window and leave it open, but the minute I close it the script stops doing what it is supposed to.
You need to start the script and have it keep powershell open.
I tried numerous ways to do this, but the one that actually worked was from http://www.methos-it.com/blogs/keep-your-powershell-script-open-when-executed
param ( $Show )
if ( !$Show )
{
PowerShell -NoExit -File $MyInvocation.MyCommand.Path 1
return
}
Pasting that to the top of the script is what made it work.
I start the script from command line with
powershell.exe -noexit -command "& \path\to\script.ps1"
Phiter
14.6k14 gold badges50 silver badges85 bronze badges
answered May 25, 2016 at 16:28
1
One thing I found. if you are using Write-Host within your PowerShell scripts, and are also using Task Scheduler (as shown in the posts above), you don’t get all the output from the command line.
powershell.exe -command C:\scripts\script.ps1 >> "C:\scripts\logfile.log"
In my case, I was only seeing output from commands that ran successfully from the PowerShell script.
My conclusion so far is PowerShell uses Out-File to output to another command or in this case a log file.
So if you use *> instead of >> you get all the output from the CLI for your PowerShell script, and you can keep using Write-Host within your script.
powershell.exe -command C:\scripts\script.ps1 *> "C:\scripts\logfile.log"
You can also run the script in the background, regardless of user login.
Within your task in Task Scheduler set «Run whether user is logged on or not», and then in the password prompt type your hostname\username then your password (In my case an account with Admin permissions).
I used Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
to get around the script execution problem. I still would have preferred to run it on a per-process basis though. A problem for another time.
NiMux
8467 silver badges16 bronze badges
answered Jun 16, 2022 at 1:36
A relatively short path to specifying a Powershell script to execute at startup in Windows could be:
- Click the Windows-button (Windows-button + r)
- Enter this:
shell:startup
-
Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut
-
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):
answered Sep 24, 2018 at 8:04
Tore AurstadTore Aurstad
3,2391 gold badge28 silver badges22 bronze badges
This worked for me. Created a Scheduled task with below details:
Trigger : At startup
Actions:
Program/script : powershell.exe
Arguments : -file
answered Nov 2, 2018 at 8:47
You can see scripts and more scheduled for startup inside Task Manager in the Startup tab. Here is how to add a new item to the scheduled startup items.
First, open up explorer to shell:startup location via start-button => run:
explorer shell:startup
Right click in that folder and in the context menu select a new shortcut. Enter the following:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile
-Command «C:\myfolder\somescript.ps1»
This will startup a Powershell script without starting up your $profile scripts for faster execution. This will make sure that the powershell script is started up.
The shell:startup folder is in:
$env:APPDATA\Microsoft\Windows
And then into the folder:
Start Menu\Programs\Startup
As usual, Microsoft makes things a bit cumbersome for us when a path contains spaces, so you have to put quotes around the full path or just hit tab inside Powershell to autocomplete in this case.
answered Dec 27, 2018 at 20:05
Tore AurstadTore Aurstad
3,2391 gold badge28 silver badges22 bronze badges
If you do not want to worry about execution policy, you can use the following and put into a batch script. I use this a lot when having techs at sites run my scripts since half the time they say script didnt work but really it’s cause execution policy was undefined our restricted. This will run script even if execution policy would normally block a script to run.
If you want it to run at startup. Then you can place in either shell:startup for a single user or shell:common startup for all users who log into the PC.
cmd.exe /c Powershell.exe -ExecutionPolicy ByPass -File "c:\path\to\script.ps1"
Obviously, making a GPO is your best method if you have a domain and place in Scripts (Startup/Shutdown); under either Computer or User Configurations\Windows Settings\Scripts (Startup/Shutdown).
If you go that way make a directory called Startup or something under **
\\yourdomain.com\netlogon\
and put it there to reference in the GPO. This way you know the DC has rights to execute it. When you browse for the script on the DC you will find it under
C:\Windows\SYSVOL\domain\scripts\Startup\
since this is the local path of netlogon.
answered Feb 11, 2020 at 9:59
Execute PowerShell command below to run the PowerShell script
.ps1
through the task scheduler at user login.
Register-ScheduledTask -TaskName "SOME TASKNAME" -Trigger (New-ScheduledTaskTrigger -AtLogon) -Action (New-ScheduledTaskAction -Execute "${Env:WinDir}\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-WindowStyle Hidden -Command `"& 'C:\PATH\TO\FILE.ps1'`"") -RunLevel Highest -Force;
-AtLogOn
— indicates that a trigger starts a task when a user logs on.
-AtStartup
— indicates that a trigger starts a task when the system is started.
-WindowStyle Hidden
— don’t show PowerShell window at startup. Remove if not required.
-RunLevel Highest
— run PowerShell as administrator. Remove if not required.
P.S.
If necessary execute PowerShell command below to enable PowerShell scripts execution.
Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Unrestricted -Force;
Bypass
— nothing is blocked and there are no warnings or prompts.
Unrestricted
— loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the internet, you’re prompted for permission before it runs.
answered Feb 23, 2020 at 12:02
Victor S.Victor S.
2,5503 gold badges22 silver badges35 bronze badges
I’m aware that people around here don’t need a tool like this, but I think it will be useful especially for novice users. Auto Start Tool is a portable freeware designed to simplify the process of automatically launching an app or script when you log in to Windows. It offers three different options for autostart:
- Task Scheduler
- Startup Folder
- Registry Run Key
The best part of the tool is that it supports PowerShell scripts (.ps1), which means you can run a PowerShell script automatically at system startup using any of the three available methods.
Download:
https://disk.yandex.com.tr/d/dFzyB2Fu4lC-Ww
Source:
https://www.portablefreeware.com/forums/viewtopic.php?f=4&t=25761
answered Mar 2, 2022 at 12:22
KlavyenKlavyen
431 silver badge7 bronze badges