Windows schedules task creation issue with powershell - powershell

I'm trying to script windows scheduled task creation with powershell, where the schedules tasks call powershell scripts that are in a directory that contains a space. So i need to create with a /tr argument like powershell.exe -noninteractive -command "& 'c:\temp\program files\a.ps1'"
Here is a sample of what i have tried
# Create the script file the schedule task will call, note path contains a space
'set-content c:\temp\program files\a.log "Just done # $(get-date)"' > 'c:\temp\program files\a.ps1'
$scriptFilePath = 'c:\temp\program files\a.ps1';
$userName = read-host 'user name'; # will need log on as batch rights
$userPassword = read-host 'user password';
# The following looks good but schtasks args gets messed up so no creation
$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -command `"& '$scriptFilePath'`"";
$taskToRun
schtasks /create /tn 'ATest' /ru $userName /rp $userPassword /sc MINUTE /mo 1 /st '00:00' /f /tr $taskToRun;
# Gets imported but mangles the tr so instead of
$taskToRun = 'c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -command \"& ''' + $scriptFilePath + '''\"';
$taskToRun
schtasks /create /tn 'ATest' /ru $userName /rp $userPassword /sc MINUTE /mo 1 /st '00:00' /f /tr $taskToRun;
If anyone knows how to escape correctly, i would appreciate a hint
Thanks in advance
Pat

I'd trade the -command option for -file:
$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -file ""$scriptFilePath"""
Also, the PowershellPack has a TaskScheduler module that's makes task scheduling much easier:
http://archive.msdn.microsoft.com/PowerShellPack
[UPDATE] Thanks
Perfect, just needed to escape with a single quote rather than double quote
$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -file '$scriptFilePath'";

Related

Az Copy Scheduled Task Created but not executing script

I am using a powershell script that will read in a service principal and use it to run azcopy sync:
$StorageAccountName = 'nkstgacct'
$ContainerName = 'netangularproject'
$StorageURL = 'https://' + $StorageAccountName + '.blob.core.windows.net/' + $ContainerName
$LocalPath = <source path>
$TenantID = ''
$AppID = ''
$Password = ''
$env:AZCOPY_SPA_CLIENT_SECRET = $Password
.\azcopy login --service-principal --application-id $AppID --tenant-id $TenantID
.\azcopy sync $LocalPath $StorageURL --recursive=true
From there, I add the script file into a windows scheduled task command to run every 5 min:
schtasks /CREATE /SC minute /MO 5 /TN "AzCopy Script 2" /TR C:\Users\nk\Documents\AzCopy\Windows\azcopyAutomatedTest.ps1
The windows scheduled task gets created but when it runs, it does not actually run the script. I've checked my storage account every-time the task runs and do not see it updated. I've also changed the file to .bat and .exe and have not seen it run as expected.
The reason this wasn't running the script was because I did not include the path to the az copy folder in the script.
so I just added the az copy command path right before the:
$env:AZCOPY_SPA_CLIENT_SECRET = $Password
and it worked.
You have to have 3 things in place.
First you have to execute the script with powershell.exe the default application for opening .ps1 files is notepad:
powershell.exe -file "C:\Users\nk\Documents\AzCopy\Windows\azcopyAutomatedTest.ps1"
Second, you have to set the Execution Policy from the default RemoteSigned to either ByPass or Unrestricted:
powershell.exe -ExecutionPolicy ByPass
e.g.
schtasks /CREATE /SC minute /MO 5 /TN "AzCopy Script 2" /TR 'powershell.exe -ExecutionPolicy ByPass -File "C:\Users\nk\Documents\AzCopy\Windows\azcopyAutomatedTest.ps1"'
Third, when you are running the powershell script as a scheduled job, it starts up in the "C:\Windows\system32" folder (Note: This also happens when you specify the "Start in" directory). So you have to have all your paths be Fully Qualified.

Running a local powershell script for all users using schtasks

Normally I use GPO to run scripts for all my users but I want to push out a powershell script and if certain conditions are not met, then it will create a schedule task for all users on that computer to run a local powershell script. (Needs to run with admin privs)
I am sure the solution is very simple but I just cannot get it to work.
I have tried all of the following including setting executionpolicy to unrestricted and moving where I am storing the script locally.
schtasks /create /f /ru "NT AUTHORITY\SYSTEM" /tn "MYTASK" /tr "powershell -file C:\ProgramData\script.ps1 -executionpolicy bypass" /sc onlogon
schtasks /create /f /tn "My Task Name" /ru Administrator /sc onlogon /tr "powershell.exe -noprofile -executionpolicy bypass -file C:\ProgramData\script.ps1"
I have also tried a .cmd file and .bat file with the following in them and calling them with the schtasks above:
powershell.exe -noprofile -executionpolicy bypass -file C:\ProgramData\script.ps1
schtasks /create /f /tn "My Task Name" /ru Administrator /sc onlogon /tr "C:\ProgramData\script.bat"
Any help is appreciated.

Run Powershell script via batch file with elevated privileges

I need to run a Powershell script to create AD user via a batch file. The thing is I need to run this PS script with elevated privileges (domain admin account). I have tried to script a '.bat' file which encloses all this information but I have been unsuccessful so far. Here is the script :
echo off
cls
echo Sign in with your ADM ID
set /p username=
powershell -noprofile -command "&{ start-process powershell -ArgumentList '-
noprofile -file C:\Users\...\Desktop\Powershell_scripts\New-ADuser\New-
Aduser_test.ps1' -verb RunAs}"
I have tried with line /netonly /user:adm#domain but It won't work.
Do you guys have any idea?
Thanks in advance.
I have finally ended up with this :
runas.exe /netonly /noprofile /user:domainadm#domain "powershell.exe -
noprofile -File "C:\Users\...\Desktop\Powershell_scripts\New-
ADuser\.ps1" -verb RunAs"
It works like a charm now!
Hope it will help anyone in need. ;)
you can start powershell with another credentials
#echo off
cls
echo Sign in with your ADM ID
set/P user="* user: "
rem set/P pass="* password: "
set "psCmd=powershell -Command "$pwd = read-host '* password' -AsSecureString; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd); [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /F "usebackq delims=" %%P in (`%psCmd%`) do set "pass=%%P"
powershell -executionpolicy bypass -Command "$p='%pass%'|convertto-securestring -asplaintext -force;$c=new-object -typename system.management.automation.pscredential('%user%',$p);start-process 'powershell' '-Command "C:\Users\...\Desktop\Powershell_scripts\New-ADuser\New-Aduser_test.ps1"' -credential $c -passthru -wait; read-host;"
exit/B
or simply
#echo off
cls
powershell -executionpolicy bypass -Command "start-process 'powershell' '-Command "C:\Users\...\Desktop\Powershell_scripts\New-ADuser\New-Aduser_test.ps1"' -credential $c -passthru -wait; read-host;"
exit/B
that will prompt for credentials

Run PowerShell script in Vagrant

I use this command to run script in Vagrant via PowerShell
vagrant.exe powershell -c "SchTasks /Create /TN 'InstallTask' /SC ONCE /ST 23:59 /IT /RL HIGHEST /TR 'powershell -Command c:/vagrant/I_O.ps1' /F | Out-Host; SchTasks /Run /TN 'InstallTask' | Out-Host;"
But it works only if I start it manually from PowerShell ISE and as a separate command.
I want to use it inside this script block
# Run Vagrant
vagrant up
# Run PowerShell in Vagrant
vagrant.exe powershell -c "Set-Location C:\vagrant"
#Set policy to Unrestricted
vagrant.exe powershell -c "Set-ExecutionPolicy Unrestricted -Force"
# Install Chocolatey
vagrant.exe powershell -c "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))"
# Turn off confirmation in Chocolatey
vagrant.exe powershell -c "chocolatey feature enable -n=allowGlobalConfirmation"
# Install .net 3.5
vagrant.exe powershell -c "choco install dotnet3.5 -force"
# Run O installation script
vagrant.exe powershell -c "SchTasks /Create /TN 'InstallTask' /SC ONCE /ST 23:59 /IT /RL HIGHEST /TR 'powershell -Command c:/vagrant/I_O.ps1' /F | Out-Host; SchTasks /Run /TN 'InstallTask' | Out-Host;"

Powershell schedule task using schtasks.exe returns error success is not recognized

I am trying to schedule another powershell script using schtasks.exe using following command:
$Command = cmd /c "$Env:WinDir/system32/schtasks.exe /create /s $ComputerName /tn $TaskName /tr $TaskRun /sc $Schedule /d $Days /st $StartTime /RU system"
Invoke-Expression $Command
It schedules the task on remote servers but throws an error:
"The term 'SUCCESS:' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
It does successfully schedule the job at correct times but throws this error.
Does anyone know how to resolve this error?
The error is displayed because when you create your $command variable, your setting it's value to the RESULT of the expression, which is SUCCESS. The command is done running before your execute Invoke-Expression. Because of that, Invoke-Expression is actually running the result (SUCCESS) as it's scriptblock, and you get an error. Proof:
PS > $command = whoami
PS > $command
computer\user
PS > $command = 'whoami'
PS > $command
whoami
You can either just call the command directly as you do when you create your $command variable, or you can save the expression(cmd /c ...) as a string and then invoke it. Ex:
$Command = 'cmd /c "$Env:WinDir/system32/schtasks.exe /create /s $ComputerName /tn $TaskName /tr $TaskRun /sc $Schedule /d $Days /st $StartTime /RU system"'
Invoke-Expression $Command