ScheduledTask script

Hi Team,
I wrote the script to get the scheduled tasks from win7/2008/R2/2003 hosts as we don’t have have this cmdlet in these OSs.

Current Challenges:

  1. When the screen size is very small (PS Console’s) then if I run the command then if the output won’t fits with in the screen then at the end of the column the data is showing like “…” which shouldn’t happen. It should behave like to show | auto enable the horizontal bars along with full Output

  2. My next goal is to write the script to start the jobs for which I will pipe this command. what are the changes need to be done(if any in this script) for the below requirement.
    Ex: Get-ScheduledTask HOSTNAME at24|Start-ScheduledTask

  3. Where to add the syntax to update-formatdata in my script. Also I don’t want to hotcode the ps1xml file path. It should take automatically where my psm1 script is located when I do import-Module

  4. In which places I need to improve my coding practices and logic’s as well.

  1. Not sure what you’re asking for here but if I could guess you could try

    Write-Output $out | Format-Table -AutoSize

  2. Again I’m unclear as to what you’re trying to accomplish. Your example posits that you will query a machine for a task and if found will run that task immediately and then you say you would like to do this using jobs? Without more info all I can advise is using

    Invoke-Command -Computername OYWAS1101 -File filetorun.ps1
    and inside your file you query for the schtasks, isolate the “Taskname” data and execute it.

  3. Sorry, not getting it again what’s the xml doc for? As for “hardcoding” the xml file path you could use the $PSScriptRoot environmental variable if you’re using Powershell 3.0+ to make the xml’s path variable relative to your script file.

  4. The bulk of your script is using string manipulation tricks to filter the output of a simple schtasks.exe command. Why not just put the /tn parameter in to your original command since it uses the wildcard character too? Example:

    $Output = schtasks.exe /query /s $ComputerName /tn $TaskName /V /FO CSV | ConvertFrom-Csv
    Going further your param block instantiates $Taskname as a string array I assume because you were looking for a specific character in the array. Try using -contains when looking for characters in a string array it’s much easier. As for better string manipulation you should look into using RegEx or “Regular Expressions”. Dr. Tobias Weltner did an excellent PowerTips Monthly on Regex back in Nov 2013 [url]http://powershell.com/cs/media/p/29098.aspx[/url].

EDIT

I have found that even though the schtasks /query /? command says there is a /tn parameter it doesn’t work so go with what you got but I still think regex will simplify your code.

Thanks Neff. I will improve the code and will submit here again in clear.

function Get-ScheduledTask
{
[CmdletBinding(DefaultParameterSetName = ‘ScheduledTask’)]
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
Position = 0,
HelpMessage = ‘Enter a computer name…’)]
[ValidateNotNullOrEmpty()]
[ValidateLength(3,12)]
[Alias(‘HostName’, ‘MachineName’)]
[string]
$ComputerName,
[Parameter(Mandatory = $true,
#ValueFromPipeline= $true,
Position = 1,
HelpMessage = ‘Enter one or more task names… You can use wildcard characters as well(Wildcard characters are allowed as pre | post fix only.)’)]
[ValidateNotNullOrEmpty()]
[Alias(‘Task’)]
[String]
$TaskName
)

BEGIN
{
	[string]$Test=""
	$Test=(Get-FormatData MS.ScheduledTasks).TypeName
	if(!($Test -eq "") -and $Test -eq "MS.ScheduledTasks")
	{
		#Do nothing. Because format data for MS.ScheduledTasks had already loaded.
		Write-Verbose "Found that the format data 'MS.SchedudedTasks' had already loaded into the memory"
	}
	else
	{
		$Path=$($PSScriptRoot+"\Format_SchTsks.ps1xml")
		If(Test-Path $Path)
		{
			Update-FormatData -PrependPath $Path
		}
		else
		{
			$color_original = $host.ui.RawUI.ForegroundColor
			$host.ui.RawUI.ForegroundColor = "RED"
			Write-Output "Unable to find the 'Format_SchTsks.ps1xml' file. Please make sure that the file Format_SchTsks.ps1xml should be with in the ScheduledTask.psm1 directory."
			$host.ui.RawUI.ForegroundColor = $color_original
			break
		}
	}
}
PROCESS
{
	$ComputerName = $ComputerName.ToUpper() #Turning the given computer name to upper case to give the best outputs.
	$PingTest = Get-WMIObject -Query "select * from win32_pingstatus where Address='$ComputerName'"
	If ($PingTest.StatusCode -eq 0)
	{
		Write-Verbose $("Host: " + $ComputerName + " is pingable")
		Write-Verbose $("Gathering scheduled tasks information from " + $ComputerName)
		$Output = schtasks.exe /query /s $ComputerName /V /FO CSV | ConvertFrom-Csv # Quering to the input server for list of all tasks.
        for ($i = 0; $i -lt $output.count; $i++)
		{
			$output[$i].taskname = $output[$i].taskname.remove(0, 1)
		}
		Write-Verbose "Adding the additional property 'Issue' to the object set"
		$output | Add-Member -MemberType NoteProperty -Name "Issue" -Value "No issues" -Force
		Write-Verbose $("Total number of tasks found in " + $Computername + " are " + $Output.count)
		if (-not ($Output -eq $Null)) #Checking whether any tasks are there or not!
		{
			Write-Verbose "Now proceeding to search for the inputed task !"
			Foreach ($T in $TaskName) #Checking for the task name match by each content in the given input.
			{
				[int]$Count = 0
				Write-Verbose $("Working on the task : " + $T)
				Write-Verbose "Checking whether wildcard character '*'  or '?' has been given either as a prefix or as a postfix to the task name."
				$WildCard = $Null
				[bool]$PreFix = $False
				[bool]$PostFix = $False
				#********************************Validating Input Starts Here******************************
				If ($T.Length -eq 1)
				{
					If ($T -eq '*')
					{
						Write-Verbose "'*' Given as wildcard"
						$Wildcard = '*'
						$PreFix = $True
					}
					ElseIf ($T -eq '?')
					{
						Write-Verbose "'?' Given as wildcard"
						$Wildcard = '?'
						$PreFix = $True
					}
					Else
					{
						Write-Verbose "No wild card given as input"
						$Wildcard = $Null
					}
				}
				ElseIf ($T.Length -ge 2)
				{
					$WildCard_temp1 = $T.Remove(1)
					$WildCard_temp2 = $T.Remove(0, ($T.Length - 1))
					If ($WildCard_temp1 -eq '*')
					{
						Write-Verbose "'*' Given as wildcard as prefix"
						$Prefix = $True
						$PostFix = $False
						$Wildcard = '*'
					}
					ElseIf ($WildCard_temp1 -eq '?')
					{
						Write-Verbose "'?' Given as wildcard as prefix"
						$Prefix = $True
						$PostFix = $False
						$Wildcard = '?'
					}
					ElseIf ($WildCard_temp2 -eq '*')
					{
						Write-Verbose "'*' Given as wildcard as postfix"
						$Prefix = $False
						$PostFix = $True
						$Wildcard = '*'
					}
					ElseIf ($WildCard_temp2 -eq '?')
					{
						Write-Verbose "'?' Given as wildcard as postfix"
						$Prefix = $False
						$PostFix = $True
						$Wildcard = '?'
					}
					Else
					{
						Write-Verbose "No wild card given as input"
						$PreFix = $False
						$PostFix = $False
						$Wildcard = $Null
					}
				}
				Else
				{
					Write-Verbose "Else is working. Should not work. Please check..."
				}
				Foreach ($Out in $output) # checking for the task match from the entire task output from the given host.
				{
					If ($PreFix -and (-not ($PostFix))) #EX: *TEXT
					{
						Write-Verbose $("Checking " + $T + " scenario. EX: " + $WildCard + "TEXT")
						If ($Out.TaskName -like $T)
						{
							$Task = $Out.TaskName
							Write-Verbose $("Schedule Task Match Found " + $Task)
							$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
							Write-Output $out
							Continue
						}
						Else
						{
							$Count++
							If ($Count -eq $Output.Count)
							{
								Foreach ($property in $Out.psobject.Properties)
								{
									$property.Value = "N/A"
									If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
									{
										If ($property.Name -eq "HostName")
										{
											$property.Value = $ComputerName
										}
										Else
										{
											$property.Value = "No Task Found"
										}
									}
								}
								$color_original = $host.ui.RawUI.ForegroundColor
								$host.ui.RawUI.ForegroundColor = "Yellow"
								$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
								Write-Output $out
								$host.ui.RawUI.ForegroundColor = $color_original
							}
						}
					}
					ElseIf (-not ($PreFix) -and $PostFix) #EX: TEXT*
					{
						Write-Verbose $("Checking " + $T + " scenario. EX: TEXT" + $WildCard)
						If ($Out.TaskName -like $T)
						{
							$Task = $Out.TaskName
							
							Write-Verbose $("Schedule Task Match Found " + $Task)
							$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
							Write-Output $out
							Continue
						}
						Else
						{
							$Count++
							If ($Count -eq $Output.Count)
							{
								Foreach ($property in $Out.psobject.Properties)
								{
									$property.Value = "N/A"
									If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
									{
										If ($property.Name -eq "HostName")
										{
											$property.Value = $ComputerName
										}
										Else
										{
											$property.Value = "No Task Found"
										}
									}
								}
								$color_original = $host.ui.RawUI.ForegroundColor
								$host.ui.RawUI.ForegroundColor = "Yellow"
								$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
								Write-Output $out
								$host.ui.RawUI.ForegroundColor = $color_original
							}
						}
					}
					ElseIf ($PreFix -and $PostFix) #EX: *TEXT*
					{
						Write-Verbose $("Checking " + $T + " scenario. EX: " + $WildCard + "TEXT" + $WildCard)
						If ($Out.TaskName -like $T)
						{
							$Task = $Out.TaskName
							Write-Verbose $("Schedule Task Match Found " + $Task)
							$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
							Write-Output $out
						}
						Else
						{
							$Count++
							If ($Count -eq $Output.Count)
							{
								Foreach ($property in $Out.psobject.Properties)
								{
									$property.Value = "N/A"
									If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
									{
										If ($property.Name -eq "HostName")
										{
											$property.Value = $ComputerName
										}
										Else
										{
											$property.Value = "No Task Found"
										}
									}
								}
								$color_original = $host.ui.RawUI.ForegroundColor
								$host.ui.RawUI.ForegroundColor = "Yellow"
								$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
								Write-Output $out
								$host.ui.RawUI.ForegroundColor = $color_original
							}
						}
					}
					ElseIf ($PreFix -eq $False -and $PostFix -eq $False) #EX:TEXT
					{
						If ($Out.TaskName -eq $T)
						{
							Write-Verbose $("Checking " + $T + " -EQ scenario. EX: TEXT")
							$Task = $Out.TaskName
							Write-Verbose $("Schedule Task Match Found " + $Task)
							$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
							Write-Output $out
							Continue
						}
						Else
						{
							$Count++
							If ($Count -eq $Output.Count)
							{
								Foreach ($property in $Out.psobject.Properties)
								{
									$property.Value = "N/A"
									If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
									{
										If ($property.Name -eq "HostName")
										{
											$property.Value = $ComputerName
										}
										Else
										{
											$property.Value = "No Task Found"
										}
									}
								}
								$color_original = $host.ui.RawUI.ForegroundColor
								$host.ui.RawUI.ForegroundColor = "Yellow"
								$out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
								Write-Output $out
								$host.ui.RawUI.ForegroundColor = $color_original
							}
						}
					}
					Else
					{
						Write-Verbose "This Else spot 2 should never run any time. Something went wrong"
						Write-Output "Something went wrong. Please report this bug to HackingIsMydream@Gmail.Com"
					}
				}
			}
		}
		Else
		{
			Write-Verbose $("No Tasks Found With The Name: " + $T)
			Write-Output $($ComputerName.ToUpper() + " : Not running any tasks")
		}
	}
	Else
	{
		Write-Warning $("Host: " + $ComputerName + " is Not pingable. Please check...")
	}
}
END { }

}

Please post your updated code as attachment or link to GitHub, Pastebin, etc. Without indentation it is more difficult to read and to verify for best practices which include code formatting.

Thanks
Daniel

Here it is with indentation. (Three cheers for IseSteroids!)

function Get-ScheduledTask
{
    [CmdletBinding(DefaultParameterSetName = 'ScheduledTask')]
    param
    (
        [Parameter(Mandatory = $true,
                ValueFromPipeline = $true,
                Position = 0,
        HelpMessage = 'Enter a computer name..')]
        [ValidateNotNullOrEmpty()]
        [ValidateLength(3,12)]
        [Alias('HostName', 'MachineName')]
        [string]
        $ComputerName,
        [Parameter(Mandatory = $true,
                #ValueFromPipeline= $true,
                Position = 1,
        HelpMessage = 'Enter one or more task names.. You can use wildcard characters as well(Wildcard characters are allowed as pre | post fix only.)')]
        [ValidateNotNullOrEmpty()]
        [Alias('Task')]
        [String[]]
        $TaskName
    )
    BEGIN
    {
        [string]$Test=""
        $Test=(Get-FormatData MS.ScheduledTasks).TypeName
        if(!($Test -eq "") -and $Test -eq "MS.ScheduledTasks")
        {
            #Do nothing. Because format data for MS.ScheduledTasks had already loaded.
            Write-Verbose "Found that the format data 'MS.SchedudedTasks' had already loaded into the memory"
        }
        else
        {
            $Path=$($PSScriptRoot+"\Format_SchTsks.ps1xml")
            If(Test-Path $Path)
            {
                Update-FormatData -PrependPath $Path
            }
            else
            {
                $color_original = $host.ui.RawUI.ForegroundColor
                $host.ui.RawUI.ForegroundColor = "RED"
                Write-Output "Unable to find the 'Format_SchTsks.ps1xml' file. Please make sure that the file Format_SchTsks.ps1xml should be with in the ScheduledTask.psm1 directory."
                $host.ui.RawUI.ForegroundColor = $color_original
                break
            }
        }
    }
    PROCESS
    {
        $ComputerName = $ComputerName.ToUpper() #Turning the given computer name to upper case to give the best outputs.
        $PingTest = Get-WMIObject -Query "select * from win32_pingstatus where Address='$ComputerName'"
        If ($PingTest.StatusCode -eq 0)
        {
            Write-Verbose $("Host: " + $ComputerName + " is pingable")
            Write-Verbose $("Gathering scheduled tasks information from " + $ComputerName)
            $Output = schtasks.exe /query /s $ComputerName /V /FO CSV | ConvertFrom-Csv # Quering to the input server for list of all tasks.
            for ($i = 0; $i -lt $output.count; $i++)
            {
                $output[$i].taskname = $output[$i].taskname.remove(0, 1)
            }
            Write-Verbose "Adding the additional property 'Issue' to the object set"
            $output | Add-Member -MemberType NoteProperty -Name "Issue" -Value "No issues" -Force
            Write-Verbose $("Total number of tasks found in " + $Computername + " are " + $Output.count)
            if (-not ($Output -eq $Null)) #Checking whether any tasks are there or not!
            {
                Write-Verbose "Now proceeding to search for the inputed task !"
                Foreach ($T in $TaskName) #Checking for the task name match by each content in the given input.
                {
                    [int]$Count = 0
                    Write-Verbose $("Working on the task : " + $T)
                    Write-Verbose "Checking whether wildcard character '*' or '?' has been given either as a prefix or as a postfix to the task name."
                    $WildCard = $Null
                    [bool]$PreFix = $False
                    [bool]$PostFix = $False
                    #********************************Validating Input Starts Here******************************
                    If ($T.Length -eq 1)
                    {
                        If ($T -eq '*')
                        {
                            Write-Verbose "'*' Given as wildcard"
                            $Wildcard = '*'
                            $PreFix = $True
                        }
                        ElseIf ($T -eq '?')
                        {
                            Write-Verbose "'?' Given as wildcard"
                            $Wildcard = '?'
                            $PreFix = $True
                        }
                        Else
                        {
                            Write-Verbose "No wild card given as input"
                            $Wildcard = $Null
                        }
                    }
                    ElseIf ($T.Length -ge 2)
                    {
                        $WildCard_temp1 = $T.Remove(1)
                        $WildCard_temp2 = $T.Remove(0, ($T.Length – 1))
                        If ($WildCard_temp1 -eq '*')
                        {
                            Write-Verbose "'*' Given as wildcard as prefix"
                            $Prefix = $True
                            $PostFix = $False
                            $Wildcard = '*'
                        }
                        ElseIf ($WildCard_temp1 -eq '?')
                        {
                            Write-Verbose "'?' Given as wildcard as prefix"
                            $Prefix = $True
                            $PostFix = $False
                            $Wildcard = '?'
                        }
                        ElseIf ($WildCard_temp2 -eq '*')
                        {
                            Write-Verbose "'*' Given as wildcard as postfix"
                            $Prefix = $False
                            $PostFix = $True
                            $Wildcard = '*'
                        }
                        ElseIf ($WildCard_temp2 -eq '?')
                        {
                            Write-Verbose "'?' Given as wildcard as postfix"
                            $Prefix = $False
                            $PostFix = $True
                            $Wildcard = '?'
                        }
                        Else
                        {
                            Write-Verbose "No wild card given as input"
                            $PreFix = $False
                            $PostFix = $False
                            $Wildcard = $Null
                        }
                    }
                    Else
                    {
                        Write-Verbose "Else is working. Should not work. Please check…"
                    }
                    Foreach ($Out in $output) # checking for the task match from the entire task output from the given host.
                    {
                        If ($PreFix -and (-not ($PostFix))) #EX: *TEXT
                        {
                            Write-Verbose $("Checking " + $T + " scenario. EX: " + $WildCard + "TEXT")
                            If ($Out.TaskName -like $T)
                            {
                                $Task = $Out.TaskName
                                Write-Verbose $("Schedule Task Match Found " + $Task)
                                $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                Write-Output $out
                                Continue
                            }
                            Else
                            {
                                $Count++
                                If ($Count -eq $Output.Count)
                                {
                                    Foreach ($property in $Out.psobject.Properties)
                                    {
                                        $property.Value = "N/A"
                                        If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
                                        {
                                            If ($property.Name -eq "HostName")
                                            {
                                                $property.Value = $ComputerName
                                            }
                                            Else
                                            {
                                                $property.Value = "No Task Found"
                                            }
                                        }
                                    }
                                    $color_original = $host.ui.RawUI.ForegroundColor
                                    $host.ui.RawUI.ForegroundColor = "Yellow"
                                    $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                    Write-Output $out
                                    $host.ui.RawUI.ForegroundColor = $color_original
                                }
                            }
                        }
                        ElseIf (-not ($PreFix) -and $PostFix) #EX: TEXT*
                        {
                            Write-Verbose $("Checking " + $T + " scenario. EX: TEXT" + $WildCard)
                            If ($Out.TaskName -like $T)
                            {
                                $Task = $Out.TaskName

                                Write-Verbose $("Schedule Task Match Found " + $Task)
                                $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                Write-Output $out
                                Continue
                            }
                            Else
                            {
                                $Count++
                                If ($Count -eq $Output.Count)
                                {
                                    Foreach ($property in $Out.psobject.Properties)
                                    {
                                        $property.Value = "N/A"
                                        If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
                                        {
                                            If ($property.Name -eq "HostName")
                                            {
                                                $property.Value = $ComputerName
                                            }
                                            Else
                                            {
                                                $property.Value = "No Task Found"
                                            }
                                        }
                                    }
                                    $color_original = $host.ui.RawUI.ForegroundColor
                                    $host.ui.RawUI.ForegroundColor = "Yellow"
                                    $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                    Write-Output $out
                                    $host.ui.RawUI.ForegroundColor = $color_original
                                }
                            }
                        }
                        ElseIf ($PreFix -and $PostFix) #EX: *TEXT*
                        {
                            Write-Verbose $("Checking " + $T + " scenario. EX: " + $WildCard + "TEXT" + $WildCard)
                            If ($Out.TaskName -like $T)
                            {
                                $Task = $Out.TaskName
                                Write-Verbose $("Schedule Task Match Found " + $Task)
                                $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                Write-Output $out
                            }
                            Else
                            {
                                $Count++
                                If ($Count -eq $Output.Count)
                                {
                                    Foreach ($property in $Out.psobject.Properties)
                                    {
                                        $property.Value = "N/A"
                                        If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
                                        {
                                            If ($property.Name -eq "HostName")
                                            {
                                                $property.Value = $ComputerName
                                            }
                                            Else
                                            {
                                                $property.Value = "No Task Found"
                                            }
                                        }
                                    }
                                    $color_original = $host.ui.RawUI.ForegroundColor
                                    $host.ui.RawUI.ForegroundColor = "Yellow"
                                    $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                    Write-Output $out
                                    $host.ui.RawUI.ForegroundColor = $color_original
                                }
                            }
                        }
                        ElseIf ($PreFix -eq $False -and $PostFix -eq $False) #EX:TEXT
                        {
                            If ($Out.TaskName -eq $T)
                            {
                                Write-Verbose $("Checking " + $T + " -EQ scenario. EX: TEXT")
                                $Task = $Out.TaskName
                                Write-Verbose $("Schedule Task Match Found " + $Task)
                                $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                Write-Output $out
                                Continue
                            }
                            Else
                            {
                                $Count++
                                If ($Count -eq $Output.Count)
                                {
                                    Foreach ($property in $Out.psobject.Properties)
                                    {
                                        $property.Value = "N/A"
                                        If ($property.Name -eq "HostName" -or $property.Name -eq "Issue")
                                        {
                                            If ($property.Name -eq "HostName")
                                            {
                                                $property.Value = $ComputerName
                                            }
                                            Else
                                            {
                                                $property.Value = "No Task Found"
                                            }
                                        }
                                    }
                                    $color_original = $host.ui.RawUI.ForegroundColor
                                    $host.ui.RawUI.ForegroundColor = "Yellow"
                                    $out.PSTypeNames.Insert(0, "MS.ScheduledTasks")
                                    Write-Output $out
                                    $host.ui.RawUI.ForegroundColor = $color_original
                                }
                            }
                        }
                        Else
                        {
                            Write-Verbose "This Else spot 2 should never run any time. Something went wrong"
                            Write-Output "Something went wrong. Please report this bug to HackingIsMydream@Gmail.Com"
                        }
                    }
                }
            }
            Else
            {
                Write-Verbose $("No Tasks Found With The Name: " + $T)
                Write-Output $($ComputerName.ToUpper() + " : Not running any tasks")
            }
        }
        Else
        {
            Write-Warning $("Host: " + $ComputerName + " is Not pingable. Please check…")
        }
    }
    END { }
}
Function Get-SchedudedTask
{
	[cmdletbinding()]
	param
	(
		[Parameter(Mandatory = $true,
		ValueFromPipeline = $true,
		Position = 0,
		HelpMessage = 'Enter a computer name..')]
		[ValidateNotNullOrEmpty()]
		[ValidateLength(3,12)]
		[Alias('HostName', 'MachineName')]
		[string]
		$ComputerName,
		[Parameter(Mandatory = $true,
		#ValueFromPipeline= $true,
		Position = 1,
		HelpMessage = 'Enter one or more task names.. You can use wildcard characters as well(Wildcard characters are allowed as pre | post fix only.)')]
		[ValidateNotNullOrEmpty()]
		[Alias('Task')]
		[String[]]
		$TaskName
	)
	BEGIN
	{	
		Set-WindowMaximized
		[string]$Test=""
		$Test=(Get-FormatData MorganStanley.Windows.ScheduledTasks).TypeName
		if(!($Test -eq "") -and $Test -eq "MorganStanley.Windows.ScheduledTasks")
		{
			#Do nothing. Because format data for MorganStanley.Windows.ScheduledTasks had already loaded.
			Write-Verbose "Found that the format data 'MorganStanley.Windows.ScheduledTasks' had already loaded into the memory"
		}
		else
		{
			$Path=$($PSScriptRoot+"\Format_SchTsks.ps1xml")
			If(Test-Path $Path)
			{
				Update-FormatData -PrependPath $Path
			}
			else
			{
				$color_original = $host.ui.RawUI.ForegroundColor
				$host.ui.RawUI.ForegroundColor = "RED"
				Write-Output "Unable to find the 'Format_SchTsks.ps1xml' file. Please make sure that the file Format_SchTsks.ps1xml should be with in the ScheduledTask.psm1 directory."
				$host.ui.RawUI.ForegroundColor = $color_original
				break
			}
		}
	}
	PROCESS
	{
		$ComputerName = $ComputerName.ToUpper() #Turning the given computer name to upper case to give the best outputs.
		$PingTest = Get-WMIObject -Query "select * from win32_pingstatus where Address='$ComputerName'"
		If ($PingTest.StatusCode -eq 0)
		{
			Write-Verbose $("Host: " + $ComputerName + " is pingable")
			Write-Verbose $("Gathering scheduled tasks information from " + $ComputerName)
			$Output = schtasks.exe /query /s $ComputerName /V /FO CSV | ConvertFrom-Csv # Quering to the input server for list of all tasks.
			#for ($i = 0; $i -lt $output.count; $i++)
			#{
			#	$output[$i].taskname = $output[$i].taskname.remove(0, 1)
			#}
			Write-Verbose "Adding the additional property 'TaskFound?' to the object set"
			$output | Add-Member -MemberType NoteProperty -Name "TaskFound?" -Value "Yes" -Force
			Write-Verbose $("Total number of tasks found in " + $Computername + " are " + $Output.count)
			if (-not ($Output -eq $Null)) #Checking whether any tasks are there or not!
			{
				Write-Verbose "Now proceeding to search for the inputed task !"
				Foreach ($T in $TaskName) #Checking for the task name match by each content in the given input.
				{
					[int]$Count = 0
					Write-Verbose $("Working on the task : " + $T)
					Write-Verbose "Checking whether wildcard character '*'  or '?' has been given either as a prefix or as a postfix to the task name."
					$WildCard = $Null
					[bool]$PreFix = $False
					[bool]$PostFix = $False
					#********************************Validating Input Starts Here******************************
					If ($T.Length -eq 1)
					{
						If ($T -eq '*')
						{
							Write-Verbose "'*' Given as wildcard"
							$Wildcard = '*'
							$PreFix = $True
						}
						ElseIf ($T -eq '?')
						{	
							Write-Verbose "'?' Given as wildcard"
							$Wildcard = '?'
							$PreFix = $True
						}
						Else
						{
							Write-Verbose "No wild card given as input"
							$Wildcard = $Null
						}
					}
					ElseIf ($T.Length -ge 2)
					{
						$WildCard_temp1 = $T.Remove(1)
						$WildCard_temp2 = $T.Remove(0, ($T.Length - 1))
						If ($WildCard_temp1 -eq '*')
						{
							Write-Verbose "'*' Given as wildcard as prefix"
							$Prefix = $True
							$PostFix = $False
							$Wildcard = '*'
						}
						ElseIf ($WildCard_temp1 -eq '?')
						{
							Write-Verbose "'?' Given as wildcard as prefix"
							$Prefix = $True
							$PostFix = $False
							$Wildcard = '?'
						}
						ElseIf ($WildCard_temp2 -eq '*')
						{
							Write-Verbose "'*' Given as wildcard as postfix"
							$Prefix = $False
							$PostFix = $True
							$Wildcard = '*'
						}
						ElseIf ($WildCard_temp2 -eq '?')
						{
							Write-Verbose "'?' Given as wildcard as postfix"
							$Prefix = $False
							$PostFix = $True
							$Wildcard = '?'
						}
						Else
						{
							Write-Verbose "No wild card given as input"
							$PreFix = $False
							$PostFix = $False
							$Wildcard = $Null
						}
					}
					Else
					{
						Write-Verbose "Else is working. Should not work. Please check..."
					}
					Foreach ($Out in $output) # checking for the task match from the entire task output from the given host.
					{
						If ($PreFix -and (-not ($PostFix))) #EX: *TEXT
						{
							Write-Verbose $("Checking " + $T + " scenario. EX: " + $WildCard + "TEXT")
							If ($Out.TaskName -like $T)
							{
								$Task = $Out.TaskName
								Write-Verbose $("Schedule Task Match Found " + $Task)
								$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
								Write-Output $out
								Continue
							}
							Else
							{
								$Count++
								If ($Count -eq $Output.Count)
								{
									Foreach ($property in $Out.psobject.Properties)
									{
										$property.Value = "N/A"
										If ($property.Name -eq "HostName" -or $property.Name -eq "TaskFound?")
										{
											If ($property.Name -eq "HostName")
											{
												$property.Value = $ComputerName
											}
											Else
											{
												$property.Value = "No"
											}
										}
									}
									$color_original = $host.ui.RawUI.ForegroundColor
									#$host.ui.RawUI.ForegroundColor = "Cyan"
									$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
									Write-Output $out
									$host.ui.RawUI.ForegroundColor = $color_original
								}
							}
						}
						ElseIf (-not ($PreFix) -and $PostFix) #EX: TEXT*
						{
							Write-Verbose $("Checking " + $T + " scenario. EX: TEXT" + $WildCard)
							If ($Out.TaskName -like $T)
							{
								$Task = $Out.TaskName
								Write-Verbose $("Schedule Task Match Found " + $Task)
								$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
								Write-Output $out
								Continue
							}
							Else
							{
								$Count++
								If ($Count -eq $Output.Count)
								{
									Foreach ($property in $Out.psobject.Properties)
									{
										$property.Value = "N/A"
										If ($property.Name -eq "HostName" -or $property.Name -eq "TaskFound?")
										{
											If ($property.Name -eq "HostName")
											{
												$property.Value = $ComputerName
											}
											Else
											{
												$property.Value = "No"
											}
										}
									}
									$color_original = $host.ui.RawUI.ForegroundColor
									#$host.ui.RawUI.ForegroundColor = "Cyan"
									$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
									Write-Output $out
									$host.ui.RawUI.ForegroundColor = $color_original
								}
							}
						}
						ElseIf ($PreFix -and $PostFix) #EX: *TEXT*
						{
							Write-Verbose $("Checking " + $T + " scenario. EX: " + $WildCard + "TEXT" + $WildCard)
							If ($Out.TaskName -like $T)
							{
								$Task = $Out.TaskName
								Write-Verbose $("Schedule Task Match Found " + $Task)
								$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
								Write-Output $out
							}
							Else
							{
								$Count++
								If ($Count -eq $Output.Count)
								{
									Foreach ($property in $Out.psobject.Properties)
									{
										$property.Value = "N/A"
										If ($property.Name -eq "HostName" -or $property.Name -eq "TaskFound?")
										{
											If ($property.Name -eq "HostName")
											{
												$property.Value = $ComputerName
											}
											Else
											{
												$property.Value = "No"
											}
										}
									}
									$color_original = $host.ui.RawUI.ForegroundColor
									#$host.ui.RawUI.ForegroundColor = "Cyan"
									$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
									Write-Output $out
									$host.ui.RawUI.ForegroundColor = $color_original
								}
							}
						}
						ElseIf ($PreFix -eq $False -and $PostFix -eq $False) #EX:TEXT
						{
							If ($Out.TaskName -eq $T)
							{
								Write-Verbose $("Checking " + $T + " -EQ scenario. EX: TEXT")
								$Task = $Out.TaskName
								Write-Verbose $("Schedule Task Match Found " + $Task)
								$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
								Write-Output $out
								Continue
							}
							Else
							{
								$Count++
								If ($Count -eq $Output.Count)
								{
									Foreach ($property in $Out.psobject.Properties)
									{
										$property.Value = "N/A"
										If ($property.Name -eq "HostName" -or $property.Name -eq "TaskFound?")
										{
											If ($property.Name -eq "HostName")
											{
												$property.Value = $ComputerName
											}
											Else
											{
												$property.Value = "No"
											}
										}
									}
									$color_original = $host.ui.RawUI.ForegroundColor
									#$host.ui.RawUI.ForegroundColor = "Cyan"
									$out.PSTypeNames.Insert(0, "MorganStanley.Windows.ScheduledTasks")
									Write-Output $out
									$host.ui.RawUI.ForegroundColor = $color_original
								}
							}
						}
						Else
						{
							Write-Verbose "This Else spot 2 should never run any time. Something went wrong"
							Write-Output "Something went wrong. Please report this bug to HackingIsMydream@Gmail.Com"
						}
					}
				}
			}
			Else
			{
				Write-Verbose $("No Tasks Found With The Name: " + $T)
				Write-Output $($ComputerName.ToUpper() + " : Not running any tasks")
			}
		}
		Else
		{
		Write-Warning $("Host: " + $ComputerName + " is Not pingable. The given host name might be a typo or host is not online. Please check.")
		}
	}
	END
	{	
	}
}

Restart

Function Restart-SchedudedTask
{
	[cmdletbinding()]
	param
	(
		[Parameter(Mandatory = $true,
		ValueFromPipeline = $true,
		Position = 0,
		HelpMessage = 'Enter a computer name..')]
		[ValidateNotNullOrEmpty()]
		[ValidateLength(3,12)]
		[Alias('HostName', 'MachineName')]
		[string]
		$ComputerName,
		[Parameter(Mandatory = $true,
		ValueFromPipeline= $true,
		Position = 1,
		HelpMessage = 'Enter one or more task names.. You can use wildcard characters as well(Wildcard characters are allowed as pre | post fix only.)')]
		[ValidateNotNullOrEmpty()]
		[Alias('Task')]
		[String[]]
		$TaskName
	)
	BEGIN
	{
		Set-WindowMaximized
	}
	PROCESS
	{
		Try
		{
			Write-Verbose "Checking the commands existence of Get, Stop & Start of SchedudedTask"
			$Check1 = Get-Command Get-SchedudedTask -ErrorAction SilentlyContinue
			$Check2 = Get-Command Stop-SchedudedTask -ErrorAction SilentlyContinue
			$Check3 = Get-Command Start-SchedudedTask -ErrorAction SilentlyContinue
			If(!($check1 -eq $Null))
			{
				Write-Verbose "'Get-SchedudedTask' - command found."
				If(!($check2 -eq $Null))
				{
					Write-Verbose "'Stop-ScheduledTask' - command found."
					If(!($check3 -eq $Null))
					{
						Write-Verbose "'Start-ScheduledTask' module found. All necessary modules are loaded now proceeding to work on input tasks."
						Foreach($T in $TaskName)
						{
							Write-Verbose $("Checking for the the task : "+$T)
							$Result = Get-SchedudedTask -ComputerName $ComputerName -TaskName $T
							If($Result -ne $Null)
							{
								Write-Verbose $('Number of matches found: '+$Result.count)
								Foreach($R in $Result)
								{
									Write-Verbose $('Working on : '+$R.TaskName)
									If($R.'TaskFound?' -eq "Yes")
									{
										If($Result.Status -eq "Running")
										{
											Write-Verbose $($R.TaskName+' : Currently this is running, hence proceeding to Restart it.')
											$Run1=schtasks.exe /End /s $ComputerName /TN $Result.TaskName
											if($Run1 -like "Success*")
											{
												Write-Verbose "Task stopped successfully."
											}
											else
											{
												Write-Verbose "Alert: Unable to stop the task"
											}
											$Run2=schtasks.exe /Run /s $ComputerName /TN $Result.TaskName
											if($Run2 -like "Success*")
											{
												Write-Verbose "Task Started successfully."
											}
											else
											{
												Write-Verbose "Alert: Unable to start the task"
											}
											Get-SchedudedTask -ComputerName $ComputerName -TaskName $T
										}
										Else
										{
											Write-Warning $($Result.TaskName + " : Task is not running hence cannot perform 'Restart-SchedudedTask'")
										}
									}
									else
									{
										Write-Error $($T + " : Task not found")
									}
								}
							}
						}
					}
					Else
					{
						Write-Error "'Start-ScheduledTask' module is not loaded. Please ensure that this module is loaded to use this cmdlet."
					}
				}
				Else
				{
					Write-Error "'Stop-ScheduledTask' module is not loaded. Please ensure that this module is loaded to use this cmdlet."
				}
			}
			Else
			{
				Write-Error "'Get-ScheduledTask' module is not loaded. Please ensure that this module is loaded to use this cmdlet."
			}
		}
		Catch
		{
			Write-Error "'Get-SchedudedTask' module is not loaded. Please ensure that this module is loaded to use this cmdlet."
			break
		}
	}
	END{}
}

Start

Function Start-SchedudedTask
{
	[cmdletbinding()]
	param
	(
		[Parameter(Mandatory = $true,
		ValueFromPipeline = $true,
		Position = 0,
		HelpMessage = 'Enter a computer name..')]
		[ValidateNotNullOrEmpty()]
		[ValidateLength(3,12)]
		[Alias('HostName', 'MachineName')]
		[String]
		$ComputerName,
		[Parameter(Mandatory = $true,
		ValueFromPipeline= $true,
		Position = 1,
		HelpMessage = 'Enter one or more task names.. You can use wildcard characters as well(Wildcard characters are allowed as pre | post fix only.)')]
		[ValidateNotNullOrEmpty()]
		[Alias('Task')]
		[String[]]
		$TaskName
	)
	BEGIN
	{
		Set-WindowMaximized
	}
	PROCESS
	{
		Try
		{
			Write-Verbose "Checking the command 'Get-SchedudedTask' existence."
			$Check = Get-Command Get-SchedudedTask -ErrorAction SilentlyContinue
			If(!($check -eq $Null))
			{
				Write-Verbose "'Get-SchedudedTask' - command found."
				#Write-Verbose $("Getting all the tasks from the host : "+$ComputerName.ToUpper())
				#$Results = Get-SchedudedTask -ComputerName $ComputerName -TaskName *
				foreach($T in $TaskName)
				{
					Write-Verbose $("Checking for the the task : "+$T)
					#$Result = $Results | ?{$_.TaskName -like $T}
					$Result=Get-SchedudedTask -ComputerName $ComputerName -TaskName $T
                    If($Result -ne $Null)
					{
						Write-Verbose $('Number of matches found: '+$Result.count)
						Foreach($R in $Result)
						{
							Write-Verbose $('Working on : '+$R.TaskName)
							If($R.'TaskFound?' -eq "Yes")
							{
								If($R.'Next Run Time' -eq 'Disabled')
								{
									Write-Verbose $($R.TaskName+' : Checking task'+"'"+'s Enabled/Disabled status.')
									Write-Warning $("'"+$R.TaskName+"'"+' : Task is disabled hence cannot start.')
								}
								else
								{
									If($R.Status -ne "Running")
									{
										Write-Verbose $($R.TaskName+' : Currently this is not running, hence proceeding to start it.')
										$Run=schtasks.exe /Run /s $ComputerName /TN $R.TaskName
										if($Run -like "Success*")
										{
											Write-Verbose "Task stopped successfully."
										}
										else
										{
											Write-Verbose "Alert: Unable to stop the task"
										}
										Get-SchedudedTask -ComputerName $ComputerName -TaskName $R.TaskName
									}
									Else
									{
										Write-Verbose $($R.TaskName+' : Currently this is running hence command won'+"'"+'t proceed to start it')
										Write-Warning $("'"+$R.TaskName+"'" + " : Task is already running")
									}
								}
							}
							else
							{
								Write-Error $($T + " : Task not found")
							}
						}
					}
					else
					{
						Break
					}
				}
			}
		}
		Catch
		{
			Write-Error "'Get-SchedudedTask' module is not loaded. Please ensure that this module is loaded to use this cmdlet."
			break
		}
	}
	END{}
}

Stop

Function Stop-SchedudedTask
{
	[cmdletbinding()]
	param
	(
		[Parameter(Mandatory = $true,
		ValueFromPipeline = $true,
		Position = 0,
		HelpMessage = 'Enter a computer name..')]
		[ValidateNotNullOrEmpty()]
		[ValidateLength(3,12)]
		[Alias('HostName', 'MachineName')]
		[string]
		$ComputerName,
		[Parameter(Mandatory = $true,
		ValueFromPipeline= $true,
		Position = 1,
		HelpMessage = 'Enter one or more task names.. You can use wildcard characters as well(Wildcard characters are allowed as pre | post fix only.)')]
		[ValidateNotNullOrEmpty()]
		[Alias('Task')]
		[String[]]
		$TaskName
	)
	BEGIN
	{
		Set-WindowMaximized
	}
	PROCESS
	{
		Try
		{
			Write-Verbose "Checking the command 'Get-SchedudedTask' existence."
			$Check = Get-Command Get-SchedudedTask -ErrorAction SilentlyContinue
			If(!($check -eq ""))
			{
				Write-Verbose "'Get-SchedudedTask' - command found."
				foreach($T in $TaskName)
				{
					Write-Verbose $("Checking for the the task : "+$T)
					$Result = Get-SchedudedTask -ComputerName $ComputerName -TaskName $T
					If($Result -ne $Null)
					{
						Write-Verbose $('Number of matches found: '+$Result.count)	
						Foreach($R in $Result)
						{
							Write-Verbose $('Working on : '+$R.TaskName)
							If($R.'TaskFound?' -eq "Yes")
							{
								If($R.'Next Run Time' -eq 'Disabled')
								{
									Write-Verbose $($R.TaskName+' : Checking task'+"'"+'s Enabled/Disabled status.')
									Write-Warning $("'"+$R.TaskName+"'"+' : Task is disabled hence cannot start.')
								}
								Else
								{
									If($R.Status -eq "Running")
									{
										Write-Verbose $($R.TaskName+' : Currently this is running, hence proceeding to stop it.')
										$Run=schtasks.exe /End /s $ComputerName /TN $R.TaskName
										if($Run -like "Success*")
										{
											Write-Verbose "Task stopped successfully."
										}
										else
										{
											Write-Verbose "Alert: Unable to stop the task"
										}
										Get-SchedudedTask -ComputerName $ComputerName -TaskName $T
									}
									Else
									{
										Write-Verbose $($R.TaskName+' : Currently this is not running hence command won'+"'"+'t proceed to stop it')
										Write-Warning $($R.TaskName + " : Task is not currently running hence cannot stop.")
									}
								}
							}
							else
							{
								Write-Error $($T + " : Task not found")
							}
						}
					}
				}
			}
		}
		Catch
		{
			Write-Error "'Get-ScheduledTask' module is not loaded. Please ensure that this module is loaded to use this cmdlet."
			break
		}
	}
	END{}
}

uptime

Function Get-Uptime
{ 
	[CmdLetBinding()]
	Param(
			[parameter(Mandatory=$False, ValueFromPipeLine=$true, position=0)]
			[string[]]$Computername="Localhost",
			[parameter(Mandatory=$False)][switch]$RunAsAnotherUser=$False
	)
	BEGIN
	{
		[int]$i=0
	}
	PROCESS
	{
		Foreach($H in $Computername)
		{
			$i++
			Write-Progress -Activity "Uptime Calculation" -Status "In-Prgress" -CurrentOperation $("Calculating uptime of the host: " + $H.toupper()) -PercentComplete (([int]$i/[int]$Computername.Count)*100)
			Write-Verbose $("Calculating system uptime : "+$H)
			If($RunAsAnotherUser)
			{
				Try
				{
					Get-WmiObject -Class Win32_PerfFormattedData_PerfOS_System -ComputerName $H -Credential (get-credential) -ea 1 -ErrorVariable  Err|Select-Object @{Name = "ComputerName"; Expression = {$_.__SERVER}},@{Name = 'SystemUpTime(Days.Hours:Minutes:Seconds)'; Expression = {New-TimeSpan -Seconds $_.SystemUpTime}}
				}
				catch
				{
					Write-Verbose $("Host '"+$H.ToUpper()+"' has failed to get the uptime. Now proceeding to check whether the host is pingable or not?...")
					$PingTest=Get-WMIObject -Query "select * from win32_pingstatus where Address='$H'"
					If($PingTest.StatusCode -eq 0)
					{
						write-verbose $("Host: '" +($H) +"' is pingable but unable to get the uptime of the host.")
						If($Err -like "*User credentials cannot be used for local*")
						{
							Write-warning "User credentials cannot be used for local connections."
						}
						Else
						{
							Write-warning $("Host: '" +($H) +"' is pingable but unable to get the uptime of the host. Please do manual checks")
						}
					}
					else
					{
						write-verbose $("Host: '" +($H) +"' is NOT pingable.")
						Write-Error $("Host: '" +($H).ToUpper() +"' is NOT pingable. Please check the host")
					}
				}
			}
			else
			{
				Try
				{
					Get-WmiObject -Class Win32_PerfFormattedData_PerfOS_System -ComputerName $H -ErrorAction 1|Select-Object @{Name = "ComputerName"; Expression = {$_.__SERVER}},@{Name = 'SystemUpTime(Days.Hours:Minutes:Seconds)'; Expression = {New-TimeSpan -Seconds $_.SystemUpTime}}
				}
				catch
				{
					Write-Verbose $("Host '"+$H.ToUpper()+"' has failed to get the uptime. Now proceeding to check whether the host is pingable or not?...")
					$PingTest=Get-WMIObject -Query "select * from win32_pingstatus where Address='$H'"
					If($PingTest.StatusCode -eq 0)
					{
						write-verbose $("Host: '" +($H) +"' is pingable but unable to get the uptime of the host.")
						Write-warning $("Host: '" +($H).ToUpper() +"' is pingable but unable to get the uptime of the host. Please do manual checks")
					}
					else
					{
						write-verbose $("Host: '" +($H) +"' is NOT pingable.")
						Write-Error $("Host: '" +($H).ToUpper() +"' is NOT pingable. Please check the host")
					}
				}
			}
		}
	}
	END{}
}

Now its ready to use. Thanks all.