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.
Related
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
Firstly: I have found a number of questions answered that do everything but allow me to bypass UAC. I am IT for a small business, but it is not my primary responsibility.
I have two machines in my domain that on startup often fail to correctly connect to the domain network. Restarting the network adapter fixes the issue until the machine restarts. Unfortunately, one of the machines is used by a non-admin, and a technically illiterate one at that.
I hoped to use a powershell script to do this. Using this website, I created script and batch files to solve the issue. Since the computer only has one network adaptor, I went simple:
internet.ps1
Get-NetAdapter | Restart-NetAdapter
internet.cmd
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%internet.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
Unfortunately, I don't fully understand the last command in the batch file. As such I struggle to research the command to pass some form of user credential. This environment is not very secure. But I don't want to give this user domain admin permissions generally, or provide them with some admin credentials which would end up on a sticky note. Either option is just inviting trouble from my older, technically illiterate colleagues. And going over to punch in credentials every day is time consuming.
I am looking for a script that cycles the network adaptor and provides the necessary credentials to make that change so a non-admin user can fix their domain and internet access without having admin credentials on a post-it note.
You could schedule a task using the Task Scheduler in Windows. When scheduling a task, you can specify credentials for the task to use when it runs. You can add a trigger for this task to have it run when the computer starts, or you can simply allow the user to manually start it.
If you decide to go this route, there is a check box you can check that runs the program with the highest possible privileges. The entire point of that last line is to start a new PowerShell window that runs as administrator so it actually has permission to restart the adapter. This means that you can get rid of almost your entire script, and just keep the part that actually restarts the adapter.
For example, when you go to create a new task in Task Scheduler, under the Actions tab, you can create a new action and enter the following:
Program/script:
PowerShell
Add arguments:
-Command "Get-NetAdapter | Restart-NetAdapter"
Note: I'm not sure if this is still the case, but in my past experience, sometimes it will try to run before Windows is fully loaded. If it doesn't seem to be doing anything on startup, you may need to add a delay to it. You can do this by running the Start-Sleep command. You can add it to the arguments field by doing the following:
-Command "Start-Sleep 5; Get-NetAdapter | Restart-NetAdapter"
Replace the number 5 with how many seconds you would like it to wait.
I've have created a Powershell script that automatically connects to office 365 and sets all users default calendar permissions to reviewer. this script runs perfectly when executed manually.
but
I am trying to launch the powershell script via task scheduler on WS-2012-R2.
i run the task but when i check a test users calendar permissions its still the same "contributor".
When task scheduler starts the task, it creates a process, that process is given a process ID.
i went to check the ID in task manager it showed as "Pick an App" under the processes tab.
i right clicked and clicked details and it shows as OpenWith.exe
i checked file association and (.PS1) is associated to WindowsPowershell
i went to the scripts file location in explorer, Rclicked and changed the OPenWith from POwershell to Windows Powershell ISE and i still get the same thing when i run through task sheduler. ("pick and app & OPenWith.exe")
i have tried editing the "actions" in Task Manager to a combination of things such as.
In task shceduler properties
Program/script: was set to: C:\Powershell script\default reviewer permissions
this doesnt work
then i changed that to C:\Windows\System32\WindowsPowerShell\v1.0\POwershell and also PowerShell_ise
with C:\Powershell script\default reviewer permissions in the "add arguments (optional) section.
and visa versa
Can anyone please tell me what i can do to make this script run.
Many thanks
What happens when you launch PowerShell from a command-line (CMD and not a PowerShell Session) like:
powershell -?
as this should show the syntax needed?
For example, mine shows (Removing the extra help information):
PowerShell
[-File ]
Specifically:
-File
Execute a script file.
You should be using something like in your Scheduled Task (note: the use of quotes as well):
PowerShell -File "D:\WORK\ps\webtest.ps1"
Hope this helps!
In PowerShell, is there an advantage to a restrictive execution policy besides trying to control which script files can run?
By default, PowerShell scripts are not allowed to run, but it seems like if a malicious party wants to run PowerShell script they can just bootstrap into it using a BAT file that calls PowerShell with the -ExecutionPolicy parameter set to "bypass".
Am I missing something, or does this defeat the execution policy mechanism? Why sign scripts (which looks like quite a hassle) when you can just make the execution policy less restrictive?
Below is a BAT script I wrote that creates an unsigned .ps1 file and runs it. It works on a machine with the execution policy of Restricted, which should disallow scripts. UAC is on and no elevation prompt is shown. It even dials out to the Internet and gets the latest headline of the "Hey, Scripting Guy!" blog.
echo write-host "`r`nPowershell code running on $(hostname).`r`n`r`nHere's the latest headline from the 'Hey, Scripting Guy!' blog: '$(([xml](New-Object Net.WebClient).DownloadString("http://blogs.technet.com/b/heyscriptingguy/atom.aspx")).feed.entry[0].title)'.`r`n`r`nPress Enter to close.`r`n"; read-host > script.ps1
powershell -ExecutionPolicy bypass -Command .\script.ps1
The execution policy will prevent someone from modifying an existing script that's being run by someone else, or as an automated process (e.g. a scheduled task). From a security standpoint, using that .bat file is no different that compiling code to do the same thing into an .exe.
Also, the -ExecutionPolicy parameter doesn't work when the execution policy is set via local/group policy on the machine (per Ansgar's comment on the question).
The default PowerShell execution policy of disallowing scripts is useful for little more than preventing accidental invocations of the script. It can be trivially violated, even on earlier versions of powershell which didn't have the per instance parameter, by doing the following
Open any script you want to run in notepad
Copy the contents to the clipboard
Paste the clipboard to an instance of powershell
Anyone who really wants to run a script can do so using this or a variety of other mechanisms. It's only really useful for preventing unintentional execution of scripts
I'm using Hudson version 1.324 for CI and have a couple of issues:
Environment:
Windows Server 2008
Powershell v1.0
Hudson 1.324 running as a service
Hudson Powershell Plugin installed
Psake (aka. "Powershell Make/Rake" available from Github) 0.23
(All current/latest versions as of this initial post)
I have a Powershell (PS) script that works to compile, run NUnit tests, and if successful, create a 7z file of the output. The PS script works from the command line, on both my local development box as well as the CI server where Hudson is installed.
1) Execution Policy with Powershell.
I initially ran a PS console on the server, ran Set-ExecutionPolicy Unrestricted, which allows any script to be run. (Yes, I realize the security concerns here, I'm trying to get something to work and Unrestricted should remove the security issues so I can focus on other problems.)
[This worked, and allowed me to fire off the PS build script from Hudson yesterday. I then encountered another problem, but we'll discuss that more in item #2.]
Once Hudson could fire off a PS script, it complained with the following error:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell "&
'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'" The term
'OzSystems.Tools\psake\psake.ps1' is not recognized as a cmdlet, funct
ion, operable program, or script file. Verify the term and try again.
At line:1 char:2
+ & <<<< 'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'"
Using the same command line, I am able to successfully execute the PS script from the command line manually. However Hudson is unable to get PS to do the same. After looking at additional PS documentation I also tried this:
"& 'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'"
and got a similar error. There does not appear to be any documentation for the Powershell plugin for Hudson. I've gone through all the Powershell plugin files and don't see anything that's configurable. I can't find a log file for Hudson to get additional information.
Can anyone help me past this?
2) I spent yesterday wrestling with #1. I came in this AM and tried to dig in again, after restarting the Hudson server/service, and now it appears that the ExecutionPolicy has been reset to Restricted. I did what worked yesterday, opened a PS console and Set-ExecutionPolicy to Unrestricted. It shows Unrestricted in the PS console, but Hudson says that it doesn't have rights to execution PS scripts. I reopened a new PS console and confirmed that the ExecutionPolicy is still Unrestriced -- it is. But Hudson evidently is not aware of this change. Restarting Hudson service again does not change Hudson's view of the policy.
Does anyone know what's going on here?
Thanks, Derek
I just ran into the problem of running powershell scripts in hudson. The thing is that you are running a 32-bit process of Java, and you've configured Hudson for 64-bit but not for 32-bit. See the following thread we created at microsoft.
http://social.technet.microsoft.com/Forums/en/winserverpowershell/thread/a9c08f7e-c557-46eb-b8a6-a19ba457e26d
If your lazy.
1. Start powershell (x86) from the start menu as administrator
2. Set the execution policy to remotesigned
Run this once and your homefree.
When Running PowerShell from a scheduled task or Hudson you want to:
Specify the -ExecutionPolicy parameter (in your case: -Ex Unrestricted)
Specify that command using either -Command { ... } or -File NOT BOTH and not without specifying which you mean.
Try this (except that I don't recommend using relative paths):
PowerShell.exe -Ex Unrestricted -Command "C:\Path\To\OzSystems.Tools\psake\psake.ps1" ".\oz-build.ps1"
To be clear, this will work too:
PowerShell.exe -Ex Unrestricted -Command "&{&'OzSystems.Tools\psake\psake.ps1' '.\oz-build.ps1'}"
The first string after -Command is interpreted as THE NAME OF A COMMAND, and every parameter after that is just passed to that command as a parameter. The string is NOT a script, it's the name of a command (in this case, a script file)... you cannot put "&'OzSystems.Tools\psake\psake.ps1'" but you can put "OzSystems.Tools\psake\psake.ps1" even if it has spaces.
To quote from the help (run PowerShell -?) emphasis mine:
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned
to the parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
I have been having the same problems as you (as you've seen from my comments). I have given up on the powershell launcher and moved to running things using the batch file launcher. Even though I had set the system to unrestricted that setting didn't seem to matter to hudson's launcher. I don't know if it runs in some other context or something, even adding things to the global profile.ps1 didn't seem to help. What I ended up doing was running
powershell " set-executionpolicy Unrestricted; & 'somefile.ps1'"
which does what I need, although it isn't ideal. I've e-mailed the plugin author about this and will update.
For question #1, try this (assuming you are using PowerShell 2.0):
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell -executionPolicy Unrestricted -file OzSystems.Tools\psake\psake.ps1 C:\{path}\oz-build.ps1"
You are using "." for the path to oz-build.ps1. I suspect you will need to provide the full path to your oz-build.ps1 file to make this work. Unless the infrastructure that executes the command above happens to have the current dir set correctly. And even if it is set correctly for the "process", that only matters to .NET/Win32 API calls and not to PowerShell cmdlets. Current dir in PowerShell is tracked differently than the process's current dir because PowerShell can have multiple runspaces running simultaneously. That sort of global, mutable value doesn't work in this concurrent scenario.
As for question #2, what account does the Hudson service run under? Make sure that account has executed Set-ExecutionPolicy RemoteSigned (or unrestricted).
I just got through this exact problem. What a pain!
If you are running a 32-bit JVM on a 64-bit Windows, make sure that you set the execution policy for the 32-bit Powershell interface. I found my 32 bit executable here:
C:\Windows\syswow64\Windowspowershell\v1.0\powerhsell.exe
The 32- and 64-bit Powershell environments are completely distinct so setting the execution policy in one has no effect on the other.