# encoding: ascii
# api: powershell
# title: ScheduledTasks
# description: PowerShell Module to manage Windows Scheduled Tasks
# version: 0.1
# type: module
# author: ChristopheCREMON
# license: CC0
# function: Get-ScheduledTasks
# x-poshcode-id: 2432
# x-archived: 2015-04-29T18:18:28
# x-published: 2011-01-03T10:03:00
#
# USAGE
# Load Module => Import-Module .\PowerScheduledTasks.psm1
# List Scheduled Tasks => Get-ScheduledTasks
# Look for a specific Scheduled Task => Get-ScheduledTasks -TaskName Task1 (support regular expressions)
# You can also connect to a remote computer, here are some examples :
# Start a Scheduled Task => Start-ScheduledTask -TaskName Task1 -HostName Computer1
# Stop a Scheduled Task => Stop-ScheduledTask -TaskName Task1 -HostName Computer1
# You can pipe Commands like this :
# Stop All Scheduled Tasks => Get-ScheduledTasks | Stop-ScheduledTask
#
# Windows Scheduled Tasks Management PowerShell Module
# http://powershell.codeplex.com

Function Get-ScheduledTasks
{
	[CmdletBinding()]
	param (
		[ValidateNotNullOrEmpty()]
		[string] $TaskName,
		[string] $HostName )
	
	process
	{
		if ( $HostName ) { $HostName = "/S $HostName" }
		$ScheduledTasks = SCHTASKS.EXE /QUERY /FO CSV /NH $HostName
		foreach ( $Item in $ScheduledTasks )
		{
			if ( $Item -ne "" )
			{
				$Item = $Item -replace("""|\s","")
				$SplitItem = $Item -split(",")
				$ScheduledTaskName = $SplitItem[0]
				$ScheduledTaskStatus = $SplitItem[3]
				if ( $ScheduledTaskName -ne "" )
				{
					if ( $ScheduledTaskStatus -eq "" )
					{
						$ScheduledTaskStatus = "Not Running"
					}
					else
					{
						$ScheduledTaskStatus = "Running"
					}
					$objScheduledTaskName = New-Object System.Object
	    			$objScheduledTaskName | Add-Member -MemberType NoteProperty -Name TaskName -Value $ScheduledTaskName
					$objScheduledTaskName | Add-Member -MemberType NoteProperty -Name TaskStatus -Value $ScheduledTaskStatus
					$objScheduledTaskName | Where-Object { $_.TaskName -match $TaskName }
				}
			}
		}
	}
}
Function Start-ScheduledTask
{
	[CmdletBinding()]
	param (
		[ValidateNotNullOrEmpty()]
		[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
		[string] $TaskName,
		[string] $HostName )

	process
	{
		if ( $HostName ) { $HostName = "/S $HostName" }
		SCHTASKS.EXE /RUN /TN $TaskName $HostName
	}
}
Function Stop-ScheduledTask
{
	[CmdletBinding()]
	param (
		[ValidateNotNullOrEmpty()]
		[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
		[string] $TaskName,
		[string] $HostName )

	process
	{
		if ( $HostName ) { $HostName = "/S $HostName" }
		SCHTASKS.EXE /END /TN $TaskName $HostName
	}
}
Export-ModuleMember Get-ScheduledTasks, Start-ScheduledTask, Stop-ScheduledTask
