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{}
}