Running a Powershell script from Task Scheduler - powershell

I need to run a PowerShell script from Task scheduler for SharePoint online. The script :
Gets the Document version from a https://xxx.sharePoint.com/site/ggg.
Outputs to a .csv file on local drive.
Acccess https://xxx-admin.sharepoint.com to post the CSV to a xxx.Sharepoint.com/site/aaaa.
The script works perfectly in PowerShell. I can't get it to run off my machine. There is no error message, or output file on C:/.
Can this script be run of my local machine?

To run PowerShell scripts you need to do one of two things. Change the Execution policy to either "RemoteSigned" (script must be created on this machine) or "Unrestricted" (not recommend), because by default it is set to "Restricted" which will not run any scripts. The second option ignores the execution policy. To start you open up\edit your original powershell script and encapsulate it with this syntax "powershell -ExecutionPolicy ByPass { script code goes here } " Also, if you want to see if an error is generated when you run the scheduled task then you need to add this argument "-NoExit". The reason the console closes is because by default the scheduled task runs the script in a background console and this closes right after and you need the "-NoExit" command to keep it open. However, if you leave the "-NoExit" argument then it will keep open all of these consoles each time the task runs. So make sure you remove it when you are sure the script is running successfully and without errors.
Encapsulated script syntax example:
powershell -ExecutionPolicy ByPass {
# Original script code here
}
Encapsulated script that keeps the console from closing syntax example:
powershell -ExecutionPolicy ByPass -NoExit {
# Original script code here
}
Creating A Scheduled Task:
Open Task Scheduler by pressing "Windows Key + R" this will bring up the run dialog and in the "Open" text-box type "taskschd.msc"
Click "Create Task" and type in the NAME field the name you want to give this task. Then determine security options you want to use, to run as administrator use the "Run with highest privileges" option.
Click "Triggers" tab and then click "New". This is where you choose what begins the task by choosing from the drop down, by default the on a schedule is selected. Then you choose the frequency, times and other advance settings you want.
Click "Actions" tab then click "New" and for actions leave as "Start a program" in the drop-down. In the "Program/script" text-box type "powershell.exe" and in the "Add arguments (option)" field type -File "FULL FILE PATH" and add the opening and closing quotation marks too. example: -File "C:\Users\Public\Documents"
Click "Conditions" tab and leave the defaults for the most part or select other conditions.
Click "Settings" tab and normally the default is fine but you can choose other settings if you like.
https://blog.netwrix.com/2018/07/03/how-to-automate-powershell-scripts-with-task-scheduler/

Not really sure, how you run it, but to answer your question: Yes, it can if you have PowerShell and all necessary libraries installed. You may need to set Execution policy, if you haven't yet and run the script with user that has enough permissions.
Check these questions and responses:
How to run a PowerShell script

Related

Closing off a process when complete in Powershell

Good afternoon,
I have a script I am running at the moment and in my script there are two lines of code.
The first line installed OneDrive with admin privileges without asking for permission (bypasses UAC).
The second line runs the application.
My problem is when the second line is run it will state the following:
"OneDrive can't be run using full administrator rights - Please restart OneDrive without administrator rights"
Start-Process -FilePath "$env:USERPROFILE\Downloads\OneDriveSetup.exe" -ArgumentList “/peruser /childprocess /cusid:$cusid /silent” –wait
[System.Diagnostics.Process]::Start($newexepath) | Out-Null #$newexepath = "c:\users\test\appdata\local\microsoft\OneDrive\OneDrive.exe"
Is there a way to stop the process in line one when it is finished, basically telling the script to forget about bypassing UAC?
You may try to disable administrative rights temporary by using “net user administrator /active:no” in cmd command. Then, try to relaunch the OneDrive client and see whether it helps. If so, you can reactive administrative rights by using “net user administrator /active:yes” in cmd command. It should help on this issue in OneDrive.
In addition, I also found that the problem could be caused due to the highest privileges settings in Task Scheduler. You can search Task Scheduler from Start and click “Task Scheduler Library”. Then find OneDrive in the list and double click on it. In the window open, make sure “Run with highest privileges” option is unchecked and click OK to save the setting. After your reboot the computer, the error message should be gone.

Automatically execute .cmd file requiring user input

We have a .cmd file we want to be able to execute automatically using Powershell (from TFS Release).
The issue with using start-process in Powershell is that execution gets stuck waiting for user input (Press any key to continue...).
Is there any way that we can pass variables to this call or call it in a different way where we no longer require user input for this .cmd?
Don't use Start-Process.
"`n" | & 'C:\path\to\your.cmd'
Powershell isn't getting stuck, Start-Process is working correctly - it's running the process (assume cmd.exe) and waiting for that process to terminate before continuing.
cmd.exe is prompting for interactive user input (PAUSE) before continuing, again working as you have instructed it to.
The issue is you're running non-interactively, and aren't providing the input required to continue.
You can update the cmd file and add an optional parameter so you can 'skip' the PAUSE when running unattended:
if "%1"=="unattended" goto skippause
pause
:skippause
then run it using unattended:
CMD /c c:\folder\file.cmd unattended

Scheduled Task Powershell Script - Runs OK as user account, but not as SYSTEM

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

PowerShell exiting

I have a script I wrote in PowerShell ISE that works perfectly.
It even works if I copy and paste it into regular PowerShell. However when I run it with regular PowerShell by making it the default program to open it with, then double-clicking, it just opens, displays some red text, and closes.
Is there a way to stop it from closing so I can view the red text or is this a common issue that can be fixed easily?
Try running from cmd prompt using:
powershell -noexit <path to the script>
Additionally, I think the error script may be throwing could be due to execution policy on your machine blocking the script from executing. Otherwise transcript would work. Ensure that the execution policy is set appropriately using Set-ExecutionPolicy cmdlet.
The practice of setting Powershell scripts to run when double clicked is highly discouraged for security reasons. Please ensure you are aware of the risks involved before you proceed.
You cannot simply 'make Powershell as default program' through the Windows Explorer interface. The Run with Powershell context menu option uses the following command:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
The "safest" way (bearing in mind the above caveat) to do what you are trying to achieve is to use Default Programs Editor to set the Run with Powershell context menu option to be the default.

Task Scheduler Launching openwith.exe program instead of PowerShell script

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!