Cygwin/WSL调用Windows schtasks命令操作Windows计划任务系列函数(查询、启用、禁用、删除)


wintask-query(){
	# 根据任务名称关键词查询Windows计划任务
	# Usage:wintask-query xxx
	gsudo schtasks.exe /Query /V /FO LIST|awk 'BEGIN{IGNORECASE = 1;}/TaskName:.*'$1'*/,/^\s+$/{print}'	
}

wintask-del(){
	# 根据任务名称关键词删除Windows计划任务
	# Usage:wintask-del xxx
	if [ $# -ge 1 ] && [[ "$1" != "" ]];
	then
		if [[ $1 =~ ^\\ ]];
		then
			local taskName=$1
		else
			#local taskName=$(wintask-query $1|dos2unix|awk '/TaskName/{printf $2;exit}')
			local taskNames=$(wintask-query $1|dos2unix|awk '/TaskName/{print $2}') #适配关键词匹配到多个任务的情况
		fi
		local taskCount=(${taskNames[@]})
		if [ ${#taskCount[*]} -gt 1 ];
		then
			echo -e "警惕操作:\"$1\" 匹配到多个任务!(${#taskCount[*]})"
			echo "${taskCount[*]}"|sed -r 's/ /\n/g'
			read -p "是否继续操作?(y/n,yes/no),默认为no  " delcontinue
			if [[ ! "${delcontinue,,}" == "y" && ! "${delcontinue,,}" == "yes" ]];
			then
				return
			fi
		fi
		for taskName in $taskNames
		do
			gsudo schtasks.exe /Delete /TN "$taskNames" /F
		done
	else
		echo -e "Need Paramter: Task Name KeyWord or Full Path!"
	fi
}

wintask-run(){
	# 根据任务名称关键词立即运行Windows计划任务;TODO:具体功能未完成!
	# Usage:wintask-run xxx
	if [ $# -ge 1 ] && [[ "$1" != "" ]];
	then
		if [[ $1 =~ ^\\ ]];
		then
			local taskName=$1
		else
			#local taskName=$(wintask-query $1|dos2unix|awk '/TaskName/{printf $2;exit}')
			local taskNames=$(wintask-query $1|dos2unix|awk '/TaskName/{print $2}') #适配关键词匹配到多个任务的情况
		fi
		local taskCount=(${taskNames[@]})
		if [ ${#taskCount[*]} -gt 1 ];
		then
			echo -e "提示:\"$1\" 匹配到多个任务!(${#taskCount[*]})"
			echo "${taskCount[*]}"|sed -r 's/ /\n/g'
			read -p "请选择你要执行的任务?(y/n,yes/no),默认为no  " delcontinue
			if [[ ! "${delcontinue,,}" == "y" && ! "${delcontinue,,}" == "yes" ]];
			then
				return
			fi
		fi
		for taskName in $taskNames
		do
			gsudo schtasks.exe /Run /TN "$taskNames"
		done
	else
		echo -e "Need Paramter: Task Name KeyWord or Full Path!"
	fi
}

wintask-enable(){
	# 根据任务名称关键词启用Windows计划任务
	# Usage:wintask-enable xxx
	if [ $# -ge 1 ] && [[ "$1" != "" ]];
	then
		if [[ $1 =~ ^\\ ]];
		then
			local taskName=$1
		else
			#local taskName=$(wintask-query $1|dos2unix|awk '/TaskName/{printf $2;exit}')
			local taskNames=$(wintask-query $1|dos2unix|awk '/TaskName/{print $2}') #适配关键词匹配到多个任务的情况
		fi
		for taskName in $taskNames
		do
			gsudo schtasks.exe /CHANGE /ENABLE /TN "$taskName"
		done
	else
		echo -e "Need Paramter: Task Name KeyWord or Full Path!"
	fi
}

wintask-disable(){
	# 根据任务名称关键词禁用Windows计划任务
	# Usage:wintask-disable xxx
	if [ $# -ge 1 ] && [[ "$1" != "" ]];
	then
		if [[ $1 =~ ^\\ ]];
		then
			local taskName=$1
		else
			#local taskName=$(wintask-query $1|dos2unix|awk '/TaskName/{printf $2;exit}')
			local taskNames=$(wintask-query $1|dos2unix|awk '/TaskName/{print $2}') #适配关键词匹配到多个任务的情况
		fi
		for taskName in $taskNames
		do
			gsudo schtasks.exe /CHANGE /DISABLE /TN "$taskName"
		done
	else
		echo -e "Need Paramter: Task Name KeyWord or Full Path!"
	fi	
}