PS: Call PS1 With Batch
Description:
I almost never run Powershell script directly. Instead I usually create a batch file with the same filename as the Powershell script and place it in the same directory (usually C:\Scripts). This allows you to run the script and exit interactively. If you plan to set a powershell script as a scheduled task, just remove the PAUSE at the end.
To Resolve:
-
Save the following as a .bat and run it. It will call any .ps1 file in the same directory that has the same name.
1 2 3 4 5 6 7 8 9 10 11
:: For functions (default) pushd "%~dp0" @ECHO OFF PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -Command ". "%~dpn0.ps1"; Clean-tempfiles "' -Verb RunAs}" popd :: For scripts pushd "%~dp0" @ECHO OFF PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}" popd
-
You can stop at step 1 if you run scripts interactively, but most of the time you want them to be scheduled tasks. This is how I set it up in my environment:
- Create a directory called C:\scripts and edit the NTFS permissions to allow only: SYSTEM, Domain Admins, and Enterprise Admins
- Place all your PS Scripts in there with batch files with the exact same file name (or just edit the file to hard code the file name, meh) in the above directory.
- Create a scheduled task:
- User is System, Run with Highest Privileges checked
- Schedule: Usually Daily 12:10 AM, Repeat every 10 minutes for one day for constant scripts or just daily/weekly for regular scripts.
- Actions: Point to the batch file: C:\scripts\powercheck.bat (for example) and start-in = C:\scripts\
- That’s it, scripts will run reliably over and over. Never had issues with Scheduled Tasks or running any scripts….
-
To do this via Powershell:
1 2 3 4 5
$taskName = "RunMyScript2" $taskAction = New-ScheduledTaskAction –Execute C:\scripts\test.bat -WorkingDirectory "C:\scripts\" $taskTrigger = New-ScheduledTaskTrigger -At 2am -Daily $taskUser = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -RunLevel Highest Register-ScheduledTask –TaskName $taskName -Action $taskAction –Trigger $taskTrigger -Principal $taskUser
- Running as a user instead but still “run whether use is logged in or not”
1 2 3 4 5
$taskName = "RunMyScript4" $taskAction = New-ScheduledTaskAction –Execute C:\scripts\test.bat -WorkingDirectory "C:\scripts\" $taskTrigger = New-ScheduledTaskTrigger -At 2am -Daily $taskUser = New-ScheduledTaskPrincipal -UserID "SomePC\Gerry" -RunLevel Highest -LogonType S4U Register-ScheduledTask –TaskName $taskName -Action $taskAction –Trigger $taskTrigger -Principal $taskUser
Comments