Schtasks command line folderpath with spaces - command-line

I want to copy and replace a file from one folder to another folder via the command line using copy and schtasks. I'm having trouble with the spaces in the folderpaths. For some reason I get an: ERROR: Invalid argument/option. The spaces are between "test 1" and "test 2"
This is my line:
schtasks /create /tn CopyFile /tr "copy "C:\Users\pc\desktop\test 1\test2022.xlsx" "C:\Users\pc\desktop\test 2\test2022.xlsx"" /sc MINUTE /mo 1
I also tried this with xcopy but got the same result:
"xcopy /y"
What am I doing wrong? Thank you in advance!

Related

How to set task scheduler's arguments from Power Shell [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to set "Add arguments" in the task scheduler.
Because we have a lot of windows servers and have to set add arguments on each server.
I know it has to manage command for task scheduler "tasks" but I don't know how to add only "Add arguments".
I want to know the command that can do what I want to do (first sentence).
Please ask me anything what you want to know about this problem. Thank you.
Learn by example (copied & pasted from an open elevated cmd window; note that ^^> is my admin command prompt):
^^> schtasks /query /TN SO_31969962 /V /FO LIST | findstr /R /C:"^Task To Run:" /C:"Start In"
Task To Run: D:\bat\SO\31969962.bat "1 st" second
Start In: D:\bat\SO\files
^^> schtasks /change /TN "\SO_31969962" /TR "D:\bat\SO\31969962.bat \"first\" second"
SUCCESS: The parameters of scheduled task "\SO_31969962" have been changed.
^^> schtasks /query /TN SO_31969962 /V /FO LIST | findstr /R /C:"^Task To Run:" /C:"Start In"
Task To Run: D:\bat\SO\31969962.bat "first" second
Start In: N/A
^^>
Here the Task To Run: … line corresponds to
Unfortunately, schtasks.exe fails in specifying “start-in” directory as you can see in above example (read entire thread of this link, google for schtasks start in directory).
Following PowerShell code snippet changes both Arguments and WorkingDirectory:
$Task = Get-ScheduledTask -TaskPath '\' -TaskName 'SO_31969962'
$Task.Actions[0].Arguments = 'bubu "foo bar"'
$Task.Actions[0].WorkingDirectory = '"D:\bat\Unusual Names"'
Set-ScheduledTask -InputObject $Task | Out-Null
Edit: following commented batch script shows possible approach of how-to construct a valid PowerShell one-line command (no need to run an existing .ps1 script):
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
rem related to D:\PShell\SO\41677069_ScheduledTask_Admin.ps1
rem show current parameters of a task (before change)
schtasks /query /TN "\SO_31969962" /V /FO LIST | findstr /R /C:"^Task To Run:" /C:"^Start In"
rem set auxiliary variables (note properly escaped inner double quotes)
set "_taskGet=$Task = Get-ScheduledTask -TaskPath '\' -TaskName 'SO_31969962'"
set "_taskArg=$Task.Actions[0].Arguments = '\""foo bar\"" bubu'"
set "_taskDir=$Task.Actions[0].WorkingDirectory = '\""D:\odds and ends\""'"
set "_taskSet=Set-ScheduledTask -InputObject $Task"
rem apply auxiliary variables (used merely to keep next line readable)
PowerShell -ExecutionPolicy Bypass -command "%_taskGet%;%_taskArg%;%_taskDir%;%_taskSet%"
rem show current parameters of a task (after change)
schtasks /query /TN "\SO_31969962" /V /FO LIST | findstr /R /C:"^Task To Run:" /C:"^Start In"
Result (read powershell /? or Get-Help 'about_powershell.exe' -ShowWindow; read also about_Execution_Policies):
^^> powershell -ExecutionPolicy Bypass -File "D:\PShell\SO\41677069_ScheduledTask_Admin.ps1"
^^> D:\bat\SO\41677069_ScheduledTask_Admin.bat
Task To Run: D:\bat\SO\31969962.bat bubu "foo bar"
Start In: "D:\bat\Unusual Names"
TaskPath TaskName State
-------- -------- -----
\ SO_31969962 Disabled
Task To Run: D:\bat\SO\31969962.bat "foo bar" bubu
Start In: "D:\odds and ends"
^^>
You'll need to modify the task action, not the task itself:
# Retrieve task
$Task = Get-ScheduledTask -TaskName "myScheduledTask"
# Retrieve action, modify argument
$Task.Actions[0] = "new arguments string go here"
# Update task
Set-ScheduledTask $Task

Zabbix script timeout

I'm trying to run powershell script for cleaning disk on agent from Zabbix. Seems that script is running too long and instead response I got error.
powershell -NonInteractive C:\Scripts\CleanDisk.ps1 -deleteLogsOlderThanDays 10
Script deletes some logs and temp folders and prints statistics. If there is only few folders to delete it work fines. But if script runs too long then dialog windows with script result ends with error Get value from agent failed: ZBX_TCP_READ
Guess that it's because connection to client timeout. Is there some way how to get over this limitation?
Thx
My colleagues found usable workaround. Instead of starting script which will run long time it's better to only schedule script with schtask.exe. So I modified script, now it contains two parts. One is responsible for scheduling and starting scheduled task (schedule it self but with different arguments), second heavy and long running does the action. Result of scheduling will appear in execution script dialog box in zabbix, result of long running action is going to log file...
Here is example of powershell script StartCleanDisk.ps1. In this case task will be scheduled and immediately executed by scheduler.
StartCleanDisk.ps1 -deleteLogsOlderThanDays 10 -startAsTask 1
In this case task will directly executed.
StartCleanDisk.ps1 -deleteLogsOlderThanDays 10 -startAsTask 0
StartCleanDisk.ps1 content:
[CmdletBinding()]
param
(
[parameter(Mandatory=$true)]
[int]
$deleteLogsOlderThanDays,
[bool]
$startAsTask = $false
)
if ($startAsTask)
{
Write-Output "Scheduling task for cleaning disk ...";
$taskname = "CleanDisk"
$logFile = "X:\logs\Tasks\cleaningDisk.log";
$task = "powershell $PSScriptRoot\StartCleanDisk.ps1 -deleteLogsOlderThanDays $deleteLogsOlderThanDays -startAsTask 0 > $logFile 2>&1";
& schtasks /create /ru "System" /tn $taskname /tr $task /sc once /ST 23:59 /F /V1 /Z;
Write-Output "Task Clean disk created...";
& schtasks /run /tn $taskname;
Write-Output "Task $taskname started... Please chek $logFile";
exit 0;
}
#####################
# Script begins here
# PUT HERE COMMANDS FOR DELETING
#####################
Start as a hidden process
UserParameter=Key[*],powershell -NoProfile -ExecutionPolicy Bypass Start-Process powershell -ArgumentList \\Path\SYSVOL\..\scripts\Files\Zabbix\Key.$1.ps1 "$2" "$3" -Windowstyle Hidden
Where Key[*] is an active item in Zabbix agent for start powershell at windows host,
$1 for variation of name PowerShell scrips, "$2" "$3" "next" for any parameters
if $1="Ring" then the name of the script will Key.Ring.ps1

2 url's in powershell with cmd

I have create the following schedule task but I would like to add a second url which will run after the end of the first. Could anyone help με how can I do it??
Thanks in advance.
schtasks /create /tn "My Task Title" /tr "powershell -ExecutionPolicy unrestricted -Command \"(New-Object Net.WebClient).DownloadString(\\\"Url1\\\")\"" /sc DAILY /ru username /rp pass
If you have multiple URLs it would be best to move some of the logic into a PowerShell script file to push some of the logic away from the command line. Not that you could put this all in the command line but for ease and readability using the -File parameter of powershell would be a better way to go. First you would need to create a file called "Get-WebStrings.ps1" with the following contents.
# Check to be sure we have at least one argument.
If($args.Count -gt 0){
# Treat each argument as a URL that we need to download.
ForEach($singleURL in $args){
# Download the string
(New-Object Net.WebClient).DownloadString($singleURL)
# Optional depending on your needs
# (New-Object Net.WebClient).DownloadString($singleURL) | Out-Null
}
}
What this script will do it take the arguments sent to it as treat each one as a url and download the data. By default this would output to console. If merely performing the download is all you wish then you could pipe the output into Out-Null (see commented code above).
Next you would need to create the task in the command line much like you have already done. Note that this file needs to be accessible on the local system where the task is being called! Each URL is placed inside single quotes in the string.
schtasks /create /tn "My Task Title" /tr "powershell -ExecutionPolicy unrestricted -File 'C:\Temp\Get-WebStrings.ps1' 'https://www.google.com' 'http://www.purple.com'" /sc daily /ru username /rp pass
If you were to look at the Action inside Task Scheduler it would look like this after that was run.
-ExecutionPolicy unrestricted -File "C:\Temp\Get-WebStrings.ps1" "https:\\www.google.com" "https:\\employee.firstair.ca"

How to execute a scheduled task with "schtasks" without opening a new command line window?

I have a batch file that creates a scheduled task using schtasks like this:
schtasks /create /tn my_task_name
/tr "...\my_path\my_task.bat"
/sc daily
/st 10:00:00
/s \\my_computer_name
/u my_username
/p my_password
It works OK except the fact that when my_task.bat is executed - a new command line window is opened (and closed after execution).
I would like to avoid opening this new window (i.e. to run the task in quiet mode, in the background).
I thought to use
start /b ...\my_path\my_task.bat
but I don't know how, because since I have to call start from the batch file I need to precede it with cmd /c, which again causes the new window to open.
How could I solve this problem ?
You can do this by specifying /RU option for schtasks. This option
specifies the user account (user
context) under which the task runs.
For the system account, valid values
are "", "NT AUTHORITY\SYSTEM" or
"SYSTEM".
And thus, try this
schtasks /create /tn my_task_name
....
/st 10:00:00
/ru "SYSTEM"
....
You can use the Windows Shell Scripting extensions to execute a batch file in invisible mode.
Create a plain text file and name it <scriptname>.vbs
Paste the following code in the .vbs file
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Batch Files\syncfiles.bat" & Chr(34), 0
Set WshShell = Nothing
Change the name and path of you batch file according to your need
Save the .vbs file and schedule the same in schtasks

Why "schtasks" does not run my job?

I scheduled a task on Windows-XP using schtasks utility, but the task does not run. Here is what I see in the SchedLgU.Txt log file:
"MySQL Automatic Backup.job" (WampServer) 10/2/2010 6:36:43 PM ** ERROR **
Unable to start task.
The specific error is:
0x800700c1: (Unable to find an error message)
Try using the Task page Browse button to locate the application.
I found out that the reason for this error is spaces in the path to my script. The command that I used to set up the task look like:
schtasks /create /tn "MySQL Automatic Backup"
/tr "d:\path with spaces to my script\my script.bat" /sc daily ...
If I replace the spaces with underscores, for example, the problem disappears.
How could I solve this problem ?
And another question: What does the Start In column means in the output for schtasks /query /v ?
Thanks !
I found the answer:
Spaces in file paths can be used by using two sets of quotes,
one set for CMD.EXE and one for SchTasks.exe.
The outer quotes for CMD need to be double quotes;
the inner quotes can be single quotes or escaped double quotes.
i.e. it should be like this:
schtasks /create /tn "MySQL Automatic Backup"
/tr "\"d:\path with spaces to my script\my script.bat\"" /sc daily ...