I've created numerous scripts in PowerShell that are working as intended if I execute them directly, however, when I try and setup a schedule to run these in Task Scheduler (to run with highest privileges) it doesn't seem to be running anything at all.
I'm running the following in my actions:
powershell.exe -ExecutionPolicy Bypass -File C:\PS\Mailboxes\CheckForwardingList.ps1
I'm getting a "Last Run Result" of 0x0 and the particular purpose of the above script is to generate a TXT file from EXO which it then mails out via SMTP and I've yet to receive any emails and I also don't see any TXT being generated in the folder where the script is located.
I do have two additional scripts setup which aren't running but once I've addressed the issue on the above this should quickly rectify the problems.
I like to test my PowerShell scripts from a command prompt first.
For example a script called C:\Tests\Test-PowerShellScriptsRunning.ps1 that only contains the following one liner helps me to test if scripts can run successfully on a machine
Write-Host -ForegroundColor Yellow "If you see this, then your script is running"
Next, I run this script from a command prompt, to get the syntax right in my scheduled task:
powershell.exe -nologo -file c:\Tests\Test-PowerShellScriptsRunning.ps1
Of course, you can add the -Executionpolicy bypass parameter, but I prefer to test the execution policy first.
However, as you are running a script that connects to ExchangeOnline, I suspect it has to do with the user you are running this task under. Does the script run if you run this task under your credentials or are the credentials stored on the system or in the script?
You might want to check this article to see how you can register an app and authenticate without storing your credentials on the machine to run the script unattended: App-only authentication for unattended scripts in the EXO V2 module
Related
I am pulling my hairs as I could not figure out what happens in powershell on target machine task (v1.0 and 2.0) in my release.
every time I run the task, it throws me the error:
AuthorizationManager check failed. ---> System.Management.Automation.PSSecurityException: AuthorizationManager check failed. ---> System.Management.Automation.Host.HostException: A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning message. Do you want to run \\server\c$\Program Files\exampleps.ps1?
I understand this may relate to execution policy, so this is what I have done so far trying to solve the issue:
I went in the remote server and turned off IE enhanced security for admins, as the service account to run this script is admin
Shift+Right-click powershell to run as service account and changed execution policy from remotesigned to bypass. performed this action in both 32 and 64bit powershell. Bypass was set to local machine and current user
Added the \server\c$\Program Files\exampleps.ps1 to trusted site under internet options
I have tried to google and stackoverflow similar questions and these are what I found.
Update
After trying all 3 methods above, even when I try to run the ps script directly in console, the security warning still shows up. For some reasons, the bypass execution policy doesn't kick in. --I was able to run it in console without warnings, however, tfs task still failed
I am really frustrated and I hope anyone in the community can give me some guidance on the this.
Much appreciated.
Please try the following ways to see if they can work:
Use the "Bypass" Execution Policy Flag
PowerShell.exe -ExecutionPolicy Bypass -File \server\c$\Program Files\exampleps.ps1
Read Script from the File and Pipe to PowerShell Standard In
Get-Content \server\c$\Program Files\exampleps.ps1 | PowerShell.exe -noprofile -
Use the Invoke-Expression Command
Get-Content \server\c$\Program Files\exampleps.ps1 | Invoke-Expression
Use the "Unrestricted" Execution Policy Flag
PowerShell.exe -ExecutionPolicy UnRestricted -File \server\c$\Program Files\exampleps.ps1
There also are few other ways you can try. To view more details, you can reference to "15 Ways to Bypass the PowerShell Execution Policy".
I'm attempting to run a Powershell script as the SYSTEM account as a scheduled task, and the task runs OK, but the script runs incorrectly because it does not load some Citrix Powershell snap-ins that are needed when run as SYSTEM, but runs OK as my user account.
The script does a check to load the Citrix snap-ins, but those do not appear to work when run as SYSTEM.
if ((Get-PSSnapin "Citrix.Common.Commands" -EA silentlycontinue) -eq $null) {
try { Add-PSSnapin Citrix.* -ErrorAction Stop }
catch { write-error "Error Citrix.* Powershell snapin"; Return }
Is there anything special I need to do to get those Snap-ins loaded correctly? I'm calling the script like this, if it matters: powershell.exe -executionpolicy bypass -file C:\path\to\script.ps1.
EDIT: From running (Get-PSSnapin -registered).count as both SYSTEM and my user account, I can see that the snap-ins are loaded correctly, but still can't figure out why the script behaves differently.
OS is Server 2016, version 1607, this is the script: https://gist.github.com/4oo4/85cec464e123d7f2793745e662d6e7ab
This isn't the answer why your specific script doesn't work under the SYSTEM account but explains how you might troubleshoot your (or any other) PowerShell Script under the SYSTEM account.
Give a man a fish, and you feed him for a day. Teach a man to fish,
and you feed him for a lifetime.
The whole thing around this, is that you can actually open a interactive PowerShell command prompt under the SYSTEM account were you probably not aware of.
Run PowerShell as SYSTEM
There are a few ways to start a interactive PowerShell command prompt but probably the easiest one is using PsExec.
Using PsExec
Download
PsTools
Extract PSTools.zip and just copy PsExec into your executable path
Run PowerShell as Administrator (accept the User AccountControl prompt)
In the PowerShell administrator window, give the command: .\PsExec -i -s -d PowerShell
A new PowerShell command window will open:
(Type WhoAmI to confirm the current account)
From here you can troubleshoot the specific script:
Are there any errors when running the specific script?
Does it hang or crash at a specific command?
Are there any differences with running it under a user account?
If it appears that the script runs actually fine in the SYSTEM window, then I would check for any errors in the Task Scheduler:
Select Task Scheduler Local - Task Scheduler Library in the left pane
Select your task in the middle top pane
(Make sure you have Display All Task History in the right pane Enabled)
In the middle bottom pane check the events in the history tab
I've scheduled a batch file that has this command in a TaskScheduler and it never completes:
powershell -command "& 'C:\Test\CleanUp.ps1'"
The .ps1 file has a simple script that deletes files on different shares. The powershell script runs successfully when run in ISE or even the above mentioned command runs successfully when run at cmd prompt.
I've even tried the option below with the command and also searched a number of blogs but no luck.
-ExecutionPolicy Unrestricted
The task is scheduled to run with a service account and I've setup a number of identical jobs the same way and they worked fine. I have powershell version 4.0.
How do I get the job to complete? (successfully or with a failure)
I have seen this problem before and generally it turns out to be that, when running as a different user and/or with a different profile, the script hangs because it needs to prompt for input, e.g. a missing mandatory parameter, Get-Credential, or something like that.
I'll assume that you have run the command from an interactive shell running as the service account, as this could reveal whether there is something different about the service account profile, etc. that may interfere with the running of the script.
I'll also assume that you have tried setting up the scheduled task with your own account, under which you know the script will run correctly.
Next, look at some of the other command line options for powershell.exe:
https://technet.microsoft.com/en-gb/library/hh847736.aspx
I'm not sure whether you'll get much mileage from the -ExecutionPolicy switch, as my experience is that people tend to set the policy to Unrestricted almost as soon as the server is commissioned and then never think about it again.
You might want to look at the -NoProfile switch, as that is something I see used quite often when calling PowerShell from a .bat file or directly in the task scheduler.
Notice the -File switch, which you might consider using instead of -Command.
I have an powershell script saved in a .cmd file that downloads a file from the web and then unzips it. My azure web role executes it upon startup. This is the script:
powershell -ExecutionPolicy Bypass -c $(New-Object Net.WebClient).DownloadFile('URL.zip', 'FILE.zip') ;
(New-Object -com shell.application).namespace('c:\FOLDER').Copyhere((New-Object -com shell.application).namespace('FILE.zip').items())
When I run the script via Azure startup tasks:
The first part of the script works. The file is downloaded. The second part of the script which unzips does not run.
When I run the script via the command line when remoted into the VM:
The entire script runs.
I therefore know this is not a syntax error. The only difference I can think of between the two cases above is a permissions issue. But, I am running powershell with -ExecutionPolicy set to Bypass, which is the highest permission level. Anybody have any ideas? Thanks!
Change the command so that the output of the command is dumped into a file. Something like this should work
<YOUR_COMMAND> > out.log 2> err.log
Run the task again and checkout the output in the logs.
Also, you are using relative paths rather than absolute ones. The scheduled task probably run with the windows system folder as its working directory, so you may be getting a permissions error from that. Try using an absolute path to a directory you created.
I'm trying to put in place some monitoring for Windows Task Scheduler, I have a Powershell script that runs the following:
$serverName = hostname
$schedule = new-object -com("Schedule.Service")
$schedule.connect($serverName)
$tasks = $schedule.getfolder("\").gettasks(0)
$tasks |select name, lasttaskresult, lastruntime
This returns a list of scheduled tasks on the server it is run on, the last task result and last run time. The purpose for this is to return a dataset to our monitoring solution (Geneos) which we can use for alerting.
We have a large Win2008 estate, so I want the script centralised allowing any of the Geneos probes to call it and return a dataset for their host. To do this I wrapped the powershell in a .bat file which does the following:
\\fileserverhk\psexec.exe -accepteula -u admin -p "pwd" powershell.exe cpi \\fileserverhk\scripts\TaskSchedulerMonitor.ps1 -Destination C:\Monitor\TaskSchedulerMonitor.ps1
\\fileserverhk\psexec.exe -accepteula -u admin -p "pwd" powershell.exe -ExecutionPolicy Bypass -File C:\Monitor\TaskSchedulerMonitor.ps1
The First step copies the .ps1 file locally to get around Powershell not trusting UNC paths and the second part runs the script.
If I run the .bat file manually from a test server it executes fine (this is logged in under an admin account). However, when I fire the .bat file via Geneos (which runs under the SYSTEM account) I get:
Access is denied.
PsExec could not start powershell.exe:
So basically my question is, how do I get PsExec to switch user when it is run under the SYSTEM account? Even though PsExec has the credentials set for another account, there is obviously something preventing it from changing when run under system.
I read to try running it with the -h switch but I get the below error:
The handle is invalid.
Connecting to local system...
Starting PsExec service on local system...
Connecting with PsExec service on <server>...
Starting powershell.exe on <server>...
Error communicating with PsExec service on <server>:
In addition to the above error, I end up with the PSExec and powershell processes hung on the remote machine. The interesting part is I can see the PSExec and PSEXEC.SVC running under SYSTEM and the powershell running under admin, so it's almost there, but something isn't quite right there.
We managed to get there using a powershell wrapper on the Windows schtasks command (link here). Schtasks can be run under the SYSTEM account and will return all the necessary task information, so we no longer needed to faff about with permissions, and no more clear text passwords on the environment (bonus).
We wrapped:
schtasks.exe Query /FO CSV
in a powershell script, and used PS to format the output into the csv style expected by Geneos.