Another Task Scheduler not executing PowerShell - powershell

I have a simple PowerShell script that just creates a file. Testing this for a bigger PowerShell script.
Running on Windows Server 2012 R2 - 64-bit
its running under the Administrator account.
Run whether user is logged on or not
Run with highest privileges
Action:
Program/Script
:
Powershell.exe (I've tried it this way and the full path)
Add argumetns: -NoProfile -executionpolicy remotesigned -file C:\Scripts\test.ps1
Get-executionPolicy: RemoteSigned
added "Administrator" to:
Set-PSSSessionConfiguration -Name Microsoft.PowerShell -ShowSecurityDescriptorUI
"Administrator" has "Log on as batch job" permissions
"Administrator" is in the Admins group
PowerShell Script for testing:
$text = "Hello World"
$text | Set-Content TestMyFile.txt
$text | Out-File TestMyFile.txt
$text > TestMyFile.txt
# This is to write into a file or append to the text file created:
$text | Add-Content TestMyFile.txt
$text | Out-File TestMyFile.txt -Append
$text >> TestMyFile.txt
Nothing fancy, just trying to make sure Task Scheduler will execute a PowerShell script.
So What am I missing?

Use full paths in your output code, and for any future problems with running scripts from Task Scheduler, you should first put in logging and try/catch blocks to see what errors/outputs the script is generating before seeking further assistance. Doing this will help you find the answer faster & learn faster at the same time.
Tip: Always only name the program in the 'Program to run' aspect of Task Scheduler, as the Task Scheduler uses its own wrapper to execute the action, and in rare occasions, it can produce undesired results if you place the entire execution line in this field. Always put parameters in the parameters field.

Related

Powershell Script won't run correctly in Task Scheduler

I recently created some PowerShell code that runs perfectly fine on its own or via a command prompt (or a .bat file). Hell, it runs fine as a .cmd file too. When I create a task scheduler task for it to run automatically, the result claims that the job runs 'successfully' but there isn't any output in the folder destination.
The whole goal of the script is to look at a particular subfolder within outlook and find files with a particular name. Then it outputs the latest related attachments to a specific destination.
PowerShell Script
$olFolderInbox = 6
$limit = (Get-Date).AddDays(-1)
$filepath = "C:\Scripts\attachment Project\Spreadsheets"
$ol = New-Object -com outlook.application;
$ns = $ol.GetNamespace("MAPI");
$acct = $ns.GetDefaultFolder($olFolderInbox)
$targetfolder = $acct.Folders | where-object { $_.name -eq "Training" }
$targetfolder.Items | foreach {
if ($_.ReceivedTime -ge $limit) {
$_.attachments |
foreach {
Write-Host "attached file: ",$_.filename
If ($_.filename -match 'SessionCompletions' -or $_.filename -match 'Certifications'){
$_.saveasfile((Join-Path $filepath $_.FileName))
$ol.quit()
}
}
}
}
I've tried all kinds of things to get the Task within Task Scheduler to work and nothing so far seems to help. To start I tried using a basic bat file to run the task. Mind you, this basic format has worked with many other PowerShell related tasks that I set up to run via a bat file.
Basic Bat Script
powershell -file extract-spreadsheets.ps1
Now sometimes I've needed to include an -executionpolicy argument as well but it sadly didn't work in this case.
A little more complex Script
Powershell.exe -executionpolicy RemoteSigned -File "C:\Scripts\attachment Project\extract spreadsheets.ps1"
Note: I made sure the get-executionpolicy on the computer was / is set to RemoteSigned. I've also tried Unrestricted as well.
I've also tried even more complex / different approaches such as . . .
Even more Complex of a Script
#ECHO OFF
SET ThisScriptsDirectory=C:\Scripts\David attachment Project\
SET PowerShellScriptPath=%ThisScriptsDirectory%extract-spreadsheets.ps1
PowerShell -NoProfile -ExecutionPolicy RemoteSigned -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy RemoteSigned -File ""%PowerShellScriptPath%""' -Verb RunAs}";
And I've even tried getting a .cmd file going and trying to use that within Task Scheduler:
##:: This prolog allows a PowerShell script to be embedded in a .CMD file.
##:: Any non-PowerShell content must be preceeded by "##"
##setlocal
##set POWERSHELL_BAT_ARGS=%*
##if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%
##PowerShell -Command Invoke-Expression $('$args=#(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join(';',$((Get-Content '%~f0') -notmatch '^^##'))) & goto :EOF
$olFolderInbox = 6
$limit = (Get-Date).AddDays(-1)
$filepath = "C:\Scripts\attachment Project\Spreadsheets"
$ol = New-Object -com outlook.application;
$ns = $ol.GetNamespace("MAPI");
$acct = $ns.GetDefaultFolder($olFolderInbox)
$targetfolder = $acct.Folders | where-object { $_.name -eq "Training" }
$targetfolder.Items | foreach {
if ($_.ReceivedTime -ge $limit) {
$_.attachments |
foreach {
Write-Host "attached file: ",$_.filename
If ($_.filename -match 'SessionCompletions' -or $_.filename -match 'Certifications'){
$_.saveasfile((Join-Path $filepath $_.FileName))
$ol.quit()
}
}
}
}
In terms of Task Scheduler, I've tried a multitude of things. To start . . .
For Program / script, I tried various relative and explicit destinations / paths for bat, cmd and PowerShell.
Some examples:
Powershell.exe (again I've also done the full path as well)
C:\Scripts\attachment Project\Training_Reports.bat
Training_Reports.bat
C:\Scripts\attachment Project\extract-spreadsheets.cmd
Note: I've added the above Programs / Actions with and without quotes.
Again, the more frustrating thing is the basic format of Training_Reports.bat with the start in (optional) field of:
C:\Scripts\attachment Project or C:\Scripts\attachment Project\
Has worked with every other script / task I have set up in this format!
I've tried numerous arguments for Execution Policy such as RemoteSigned, Bypass and Unrestricted. I've Added other arguments like: -NoProfile, -noninteractive, -File, -command, -NoLogo etc etc.
Examples of what the Arguments Field has looked like within Task Scheduler:
-ExecutionPolicy Bypass -File "C:\Scripts\attachment Project\extract-spreadsheets.ps1"
-NoLogo -NonInteractive -ExecutionPolicy RemoteSigned -File "C:\Scripts\attachment Project\extract-spreadsheets.ps1"
-NoProfile -ExecutionPolicy Unrestricted -Command "C:\Scripts\attachment Project\extract-spreadsheets.ps1"
I tried using various accounts to 'run the task'.
my domain account (which my account is a global domain admin and has
full permissions)
local Admin account
another Domain Admin Account
I've tried even SYSTEM
None of the accounts above have changed the outcome. Other settings I've looked at that people claim could mess with Tasks.
Turned off 'Start the task only if the computer is on AC power'
Ran the task whether user is logged on or not
Also ran it as when user is logged on
Set it for 'Highest privileges'
I tried running the task in 'configure for' drop down menu for
Windows 10 and Windows 7 / Server 2008.
Other things I have tried:
The initial PowerShell Script had mapped drive destinations. I changed the code to use C drive locations.
Explicitly giving that user account full control over the
directories involved.
Changing ownership of the directories involved to the same user.
Changing the security permissions on the ps1, cmd, bat, outlook.exe files to always Run as Administrator.
Tried running the script with Outlook running and not running.
Note: running it manually works regardless if Outlook is running.
Why is this task within Task Scheduler not outputting correctly?

Logfile not being generated while running a powershell script with windows task scheduler

I have created the following powershell script:
stop-service ''3456''
start-sleep -s 60
stop-service "2354"
start-sleep -s 60
Restart-computer QY34 -Force
send -mailmessage -from operating.system#abc.com -To asdf#abc.com -subject test -attachment 'c:\Temp|test.log' -smtp server "127.0.0.1"
I have entered the following information on windows task scheduler
On Actions Tab;
C:\windows\System32\windowspowershell\v1.0\powershell.exe
Arguments Tab:
-file "c:\scripts\test.ps1"*>"c:\Temp\test.log"
Can anyone please help me in getting the log file while running the script via Task Scheduler?
Change the arguments from
-file "c:\scripts\test.ps1"*>"c:\Temp\test.log"
to
"c:\scripts\test.ps1" *> "c:\Temp\test.log"
and it should work as expected. Note the blank spaces before and afer *>.
I think the problem is that Powershell will read everything after -file as the file input. It'll still work, but as it just stops reading after the "file" bit, the > operator is ignored/not seen. Removing -file Powershell will still find the script using positional parameters, but it will also handle the > operator and output to file.
If you run if from a command line it'll work, I think because cmd.exe will handle the output instead of Powershell in that case, but don't quote me on that bit.

how do I make it easy for my parents to run this Powershell command?

I am not a programmer and my parents' Windows 10 PC tends to loose its start menu and cortana processes, resulting in start menu not showing up at all when the start icon is clicked.
I made a quick search and found + tested this Powershell command and it worked:
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
I wish to turn this command into a shortcut/batchfile that executes the command and restarts the PC whenever the desktop icon is double clicked, in order to avoid explaining to my parents what to do to fix the problem. Can any one help me out please?
Thank you in Advance.
you can encode the command and put the whole thing into a single batch file (no .ps1 necessary)
details here
https://blogs.msdn.microsoft.com/timid/2014/03/26/powershell-encodedcommand-and-round-trips/
or you can use this function
https://github.com/gangstanthony/PowerShell/blob/master/Encode-Text.ps1
first, either use Get-Content or Get-Clipboard (copy your whole script to the clipboard) to encode your desired script
PS> Encode-Text (Get-Clipboard | out-string)
RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
then you can use that in your batch file like so
powershell -encodedcommand RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
You could execute the PowerShell script via a batch file.
Batch file:
set powerscriptPath=C:\Example.ps1
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%powerscriptPath%""' -Verb RunAs}"
This will bypass the execution policies on the computer allowing the script to run in Administrator mode too. NOTE: You will need to edit the powerscriptPath to point to your PowerShell script location, I just used C:\Example.ps1 as an example.
You will want to add Restart-Computer -Force to the end of your PowerShell script to restart the computer
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
Restart-Computer -Force
Make a bat file which executes powershell with that file. Then add a shortcut to the bat file
I am really unsure why you would run a batch file just to call a powershell script! Talk about hokey approaches to a non-problem.
To call a powershell script is really no different than calling a batch script:
It's simply path to PowerShell, and the script path as a parameter:
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" "C:\users\austinfrench\desktop\example.ps1"
You can also use the exact same format as the target for a desktop shortcut.

Powershell script run from task scheduler unable to open word document

I am trying to use a powershell script to get the wordcount from a number of word files and then output that to a csv file. This works as expected when run from the powershell prompt, and works when called from the cmd prompt directly or from inside a perl script, however the script fails to work when called as a scheduled task.
This is not an ExecutionPolicy issue causing the script to not run at all. The script is running and produces some output, but when launched from task scheduler it is unable to open any word documents.
The relevant powershell code is below:
$folderpath = "C:\some\where\*"
$fileTypes = "*.docx"
$word = New-Object -ComObject word.application
$word.visible = $false
Get-ChildItem -path $folderpath -recurse -include $fileTypes |
foreach-object `
{
$path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
try {
$doc = $word.documents.open($_.fullname, $confirmConversion, $readOnly, $addToRecent, $passwordDocument)
} catch {
"FROM CATCH UNABLE TO OPEN $($_.fullname)" >> $wordCountFile
}
if($doc) {
$wordCount = $doc.ComputeStatistics("wdStatisticWords")
"$($_.name), $wordCount" >> $wordCountFile
$doc.close([ref]$false)
} else {
"UNABLE TO OPEN $($_.fullname)" >> $wordCountFile
}
} #end Foreach-Object
$word.Quit()
(Note that alternative methods people cite for getting the word count from word documents do not actually return the correct count as this method does when it works.)
When run as a scheduled task (set to run with highest privileges and as an administrator user) using:
cmd /c start PowerShell.exe -NoLogo -NonInteractive -ExecutionPolicy Bypass -File "C:\path\to\script\CountsInWords.ps1"
or when run with a similar command from a perl script launched by a scheduled task (my normal use case) and in both cases the task is set to run with highest privileges the powershell script does not work correctly.
The catch block is apparently never reached, as the print statement never makes it to the file, however the $doc is always null.
Additionally, when started as a task the script leaves a word process open and using a 100% cpu for 1 thread which will eventually cripple my machine.
To summarise:
run script as human (no matter how many levels of indirection) -> works perfectly
run script from task (as administrator user) -> script runs but cannot access word documents, also unable to stop word process despite always hitting the $word.Quit line.
EDIT: With #TheMadTechnician's advice about office first time startup for a new user requiring some details: On further inspection, looking at the processes in task manager, I don't see the word processes unless I click on "show processes from all users", but then they show up, but have the user listed as me. How can a process be both explicitly listed as me, but count as another user?
Attempting to set $word.visible = $true in the script didn't actually make anything appear when launched from task scheduler, so I don't know either how to verify that it is waiting for input, or how to give it that input as the correct user to make it go away...
You may be able to follow the solution named at the question How to run a Windows 2008 task from the scheduler with "interact with desktop".
Summary: If you have 64-bit Windows: Create %SystemRoot%\SysWOW64\config\systemprofile\Desktop. If you have 32-bit Windows, create %SystemRoot%\system32\config\systemprofile\Desktop.

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

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
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.
You could set it up as a Scheduled Task, and set the Task Trigger for "At Startup"
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)
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"
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.
Try this: create a shortcut in startup folder and input
PowerShell "& 'PathToFile\script.ps1'"
This is the easiest way.
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:
How to enable execution of PowerShell scripts? - Super User
Use PowerShell to Create Job that Runs at Startup | Scripting Blog
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).
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
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"
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):
This worked for me. Created a Scheduled task with below details:
Trigger : At startup
Actions:
Program/script : powershell.exe
Arguments : -file
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.
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.
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.
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 It is a Portable freeware which designed to simplify the process to automatically launch an App or script when you login to Windows. It offers 3 different options for autostart
Task Scheduler
Startup folder
Registry run key
The best part of the tool is supports powershell scripts (.Ps1) . this means that you can run a Powershell script automatically at system startup with all 3 methods.
Download
https://disk.yandex.com.tr/d/dFzyB2Fu4lC-Ww
Source:
https://www.portablefreeware.com/forums/viewtopic.php?f=4&t=25761
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"
https://lazyadmin.nl/powershell/output-to-file/
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.