How to run Powershell script (function) through Windows Task Schduler ??

Hello All,
i have Powershell script which is created as a function. I have to give parameters to run the script. And it is working fine. Now i want to run this script through windows task scheduler but it is not working. I dont know how to call powershell function
through task scheduler.
From command line i run it like this:
. c:\script\Get-ServiceStatusReport.ps1
dir function:get-service*
Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
In windows Task scheduler I am giving this: it runs but i dont receive any output :
Program/Script:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Parameter:
-file ". 'Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
Please HELP !!!

Thanks for the reply:
The script is already saved as Get-ServiceStatusReport.ps1 .
On powershell it does not run like .\Get-ServiceStatusReport.ps1 (parameter).
But i have to call it as function:
Like this:
Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
As you said:
I tried to run it like this:
Program/Script:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Parameter:
-file "c:\script\Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
But its not working , on scheduler its giving error: (0xFFFD0000)
Please HELP !!!
WHOLE SCRIPT:
function Get-ServiceStatusReport
param(
[String]$ComputerList,[String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail
$script:list = $ComputerList
$ServiceFileName= "c:\ServiceFileName.htm"
New-Item -ItemType file $ServiceFilename -Force
# Function to write the HTML Header to the file
Function writeHtmlHeader
param($fileName)
$date = ( get-date ).ToString('yyyy/MM/dd')
Add-Content $fileName "<html>"
Add-Content $fileName "<head>"
Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
Add-Content $fileName '<title>Service Status Report </title>'
add-content $fileName '<STYLE TYPE="text/css">'
add-content $fileName "<!--"
add-content $fileName "td {"
add-content $fileName "font-family: Tahoma;"
add-content $fileName "font-size: 11px;"
add-content $fileName "border-top: 1px solid #999999;"
add-content $fileName "border-right: 1px solid #999999;"
add-content $fileName "border-bottom: 1px solid #999999;"
add-content $fileName "border-left: 1px solid #999999;"
add-content $fileName "padding-top: 0px;"
add-content $fileName "padding-right: 0px;"
add-content $fileName "padding-bottom: 0px;"
add-content $fileName "padding-left: 0px;"
add-content $fileName "}"
add-content $fileName "body {"
add-content $fileName "margin-left: 5px;"
add-content $fileName "margin-top: 5px;"
add-content $fileName "margin-right: 0px;"
add-content $fileName "margin-bottom: 10px;"
add-content $fileName ""
add-content $fileName "table {"
add-content $fileName "border: thin solid #000000;"
add-content $fileName "}"
add-content $fileName "-->"
add-content $fileName "</style>"
Add-Content $fileName "</head>"
Add-Content $fileName "<body>"
add-content $fileName "<table width='100%'>"
add-content $fileName "<tr bgcolor='#CCCCCC'>"
add-content $fileName "<td colspan='4' height='25' align='center'>"
add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong>Service Stauts Report - $date</strong></font>"
add-content $fileName "</td>"
add-content $fileName "</tr>"
add-content $fileName "</table>"
# Function to write the HTML Header to the file
Function writeTableHeader
param($fileName)
Add-Content $fileName "<tr bgcolor=#CCCCCC>"
Add-Content $fileName "<td width='10%' align='center'>ServerName</td>"
Add-Content $fileName "<td width='50%' align='center'>Service Name</td>"
Add-Content $fileName "<td width='10%' align='center'>status</td>"
Add-Content $fileName "</tr>"
Function writeHtmlFooter
param($fileName)
Add-Content $fileName "</body>"
Add-Content $fileName "</html>"
Function writeDiskInfo
param($filename,$Servername,$name,$Status)
if( $status -eq "Stopped")
Add-Content $fileName "<tr>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$servername</td>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$name</td>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$Status</td>"
Add-Content $fileName "</tr>"
else
Add-Content $fileName "<tr>"
Add-Content $fileName "<td >$servername</td>"
Add-Content $fileName "<td >$name</td>"
Add-Content $fileName "<td >$Status</td>"
Add-Content $fileName "</tr>"
writeHtmlHeader $ServiceFileName
Add-Content $ServiceFileName "<table width='100%'><tbody>"
Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
Add-Content $ServiceFileName "<td width='100%' align='center' colSpan=3><font face='tahoma' color='#003399' size='2'><strong> Service Details</strong></font></td>"
Add-Content $ServiceFileName "</tr>"
writeTableHeader $ServiceFileName
#Change value of the following parameter as needed
$InlcudeArray=@()
#List of programs to exclude
#$InlcudeArray = $inlcudeService
Foreach($ServerName in (Get-Content $script:list))
$service = Get-Service -ComputerName $servername
if ($Service -ne $NULL)
foreach ($item in $service)
#$item.DisplayName
Foreach($include in $includeService)
write-host $inlcude
if(($item.serviceName).Contains($include) -eq $TRUE)
Write-Host $item.MachineName $item.name $item.Status
writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
Add-Content $ServiceFileName "</table>"
writeHtmlFooter $ServiceFileName
function Validate-IsEmail ([string]$Email)
return $Email -match "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
Function sendEmail
param($from,$to,$subject,$smtphost,$htmlFileName)
[string]$receipients="$to"
$body = Get-Content $htmlFileName
$body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
$body.isBodyhtml = $true
$smtpServer = $MailServer
$smtp = new-object Net.Mail.SmtpClient($smtphost)
$validfrom= Validate-IsEmail $from
if($validfrom -eq $TRUE)
$validTo= Validate-IsEmail $to
if($validTo -eq $TRUE)
$smtp.UseDefaultCredentials = $true;
$smtp.Send($body)
write-output "Email Sent!!"
else
write-output "Invalid entries, Try again!!"
$date = ( get-date ).ToString('yyyy/MM/dd')
sendEmail -from $From -to $to -subject "Service Status - $Date" -smtphost $SMTPMail -htmlfilename $ServiceFilename

Similar Messages

  • Run powershell script against exchange using task schedule

    I want to run this using task scheduler
    Get-MailboxStatistics -Server mailserver  | Select DisplayName, ItemCount, TotalItemSize | Sort-Object TotalItemSize -Descending | Export-CSV "\\pacetoputreport\report_$((Get-Date).ToString('MM-dd-yyyy')).csv"
    I know I have to run some variation of this to launch the exchange module
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
    How can I do this in Task Scheduler? I have tried numerous times using various combinations, but nothing seems to work.
    Thank you

    You need to put the first part where you call powershell.exe in the Program/script part of the task, but the rest of it is put into the arguments section. As explained here
    http://www.msexchange.org/kbase/ExchangeServerTips/ExchangeServer2013/Powershell/scheduling-exchange-powershell-task.html (which has versions for both 2010 and 2013, but since you list V14 in your filepath I assume you're using 2010) you'd need to
    set the arguments to :
    -version 2.0 -NonInteractive -WindowStyle Hidden -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; <Your Command>"

  • Creating scheduled task to run powershell script

    Hi all,
    been following this guide on how to create scheduled task to run a .ps1 script:
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx
    When I manually run this task,in the history it says success, but it doesnt work.
    The script should create a report and send me an e-mail.It works fine if i run it manually in Windows powershell or Powershell ISE.
    I cannot see that a new report have been created either.
    Anything im missing here?
    Been using same account to run it manually and the one using in task scheduler.
    thanks!
    Please mark as helpful if you find my contribution useful or as an answer if it does answer your question. That will encourage me - and others - to take time out to help you. Thank you! Off2work

    Hi all,
    been following this guide on how to create scheduled task to run a .ps1 script:
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx
    When I manually run this task,in the history it says success, but it doesnt work.
    Try executing the same command in cmd line, do you get a different result? or does that work as well?

  • How to run a script on Oracle server from isqlplus

    Hi I am trying to run a script on my workstation from Oracle server through isqlplus workarea. I entered following command and get the following error. i have enabled isqlplus URL by editing web.xml file already. Can please someone help how to run the script?
    @http://myaixserver.com:5560/scripts/Databasestartupstages.sql;
    SP2-0920: HTTP error 'page not found (505)' on attempt to open URL

    So far, you haven't specified your rdbms version and isqlplus behaved differently on a 9iR1, 9iR2 from the one release on 10gR1/R2. on 9i it was a servlet based on a JServ servlet executor machine, meanwhile on 10g it is a J2EE compliant application deployed on an OC4J container, so configuration is different.
    You may want to take a look at these references -->
    * Starting iSQL*Plus from a URL
    * Creating Reports using iSQL*Plus
    ~ Madrid

  • How to schedule multiple backup job through windows server backup in windows server 2008 R2

    hi expert,
    need your help, In my small  environment I am using windows 2008 R2 as a domain controller. and installed windows server feature for backup.
    Now i want to create backup at a different time.
    1. System state backup at 5.00 PM on saturday only
    2.  finance and hr data backup on daily basis at 5.00 PM.
    so how i create different job schedule through windows server backup.
    Regards,
    Triyambak
    Regards, Triyambak

    Scenario #1
    The following command will create a Task Scheduler task named
    DailyFolder1Backup with the start time of 23:00.
    This task will run DAILY with the HIGHESTprivileges. It will run the Windows Server Backup CLI to backup
    g:\folder1 to target volume
    F:.
    SCHTASKS /Create /SC DAILY /TN
    DailyFolder1Backup /RL HIGHEST /ST 23:00/TR
    "wbadmin start backup –backupTarget:F: -include:g\folder1
    -vsscopy -quiet"
    Scenario #2
    The following command will create a Task Scheduler task named
    DailyFolder2Backup with the start time of 24:00.
    This task will run DAILY with the HIGHESTprivileges. It will run the Windows Server Backup CLI to backup
    h:\folder2 to target volume
    F:.
    SCHTASKS /Create /SC DAILY /TN
    DailyFolder2Backup/RL HIGHEST /ST 24:00/TR
    "wbadmin start backup –backupTarget:F: -include:h:\folder2
    -vsscopy -quiet"
    Please feel free to let us know if you have any question or concern.
    Please VOTE as HELPFUL if the post helps you and remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading
    the thread.

  • How to run greasemonkey in Safari for Windows

    How to run greasemonkey in Safari for Windows, trying to use this for work and I have scripts I use in FF 3.5 that I would need in safari.
    Safari 4.0
    Message was edited by: metalsiren

    bump

  • How to add powershell script code in form application in C#

    Hi,
    i am creating a form application in C# and have powershell code which will create remote session on remote machine and execute few commands like set execution policy copy some share files install that files etc.
    I have to add this powershell script into form application in C#.
    Can some one please give me some example how to add the whole script which i have into C# code form application. Thanks in advance
    Thanks,

    Hi
    So the left is Run PowerShell Commands on Remote machine? Am I right ?
    Here  is a article talking about running  powershell commands on Remote Computers.
    http://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/
    About how to write in C#, please follow
    Joel Engineer's reply, using  process.Start() method  to start
    PowerShell.exe and Run PowerShell Commands to connect remote machine.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Run Powershell Script task sequence

    Hi,
    Anyone have good documentation on how to use the Run PowerShell Script task sequence ?
    Thanks

    If you are just interested in running a powershell command without creating a package, you can do this with the the Command line step by using this format in the command line:
    PowerShell -ExecutionPolicy bypass -Command "& {your powershell commands}"
    Here is an example of a multiline command to increase the agents cache size. Notice the ";"'s which are used to delineate a new line.
    PowerShell -ExecutionPolicy bypass -Command "& {$UIResourceM gr = New-Object -ComObject UIResource.UIResourceMgr;$Cache = $UIResourceMgr.GetC acheInfo();$Cache.TotalSize = "20480"}"

  • Execute a powershell script from a windows store apps

    Hello Everybody !
    I'd like to launch a powershell script from a windows store apps.
    In fact the purpose is install a windows store apps from an other windows store apps.
    Any ideas?
    Thanks

    If it's a sideloaded LOB application, you can do this using a brokered component:
    http://blogs.msdn.com/b/wsdevsol/archive/2014/04/14/cheat-sheet-for-using-brokered-windows-runtime-components-for-side-loaded-windows-store-apps.aspx
    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.
    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined
    objects and unknown namespaces.

  • Run powershell script from context menu

    Hi guys!
    I do not know if what I'm going to
    ask you is achievable.
    This is what I want:
    when I click with the right mouse button
    a file, possibly with certain extensions,
    the context menu appears, and
    here I would to create an
    object that can run the script that I have created
    and assign as an argument the selected file.
    It would also be necessary that such an object is
    similar to the"send to" button.
    Browsing the net I had found the
    script to create such an object, however,
    I have no idea on how to implement it
    and then how to run my script.
    Thanks

    Hi jrv!
    Initially, I will try to follow your suggestion but I'd prefer to use some automation, possibly related to powershell as required, because i must do this thing on many computers.
    Thanks
    A
    Y((ou would do that with Group Policy as it is just a registry update.
    ¯\_(ツ)_/¯

  • Issue with running powershell script in pssessions

    Hi Everyone,
    I am trying to run powershell script from remote machine using below commands
    C:\Users\user>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    -command "$s= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
    http://Exchservername/PowerShell/ -Authentication Kerberos ; Import-PSsession $s; "C:\Failback.ps1"
    and Below is the failback.ps1.
    $mbxs = Get-MailboxDatabase | Sort Name
    ForEach($mbx in $mbxs)
    $MBdb=$mbx.Name $ServerHosting=$mbx.Server.Name
    if($mbx.activationPreference.value -eq 1)
    If ($ServerHosting -ne $ActivationPreference.Key.Name) 
    Move-ActiveMailboxDatabase $MBdb -ActivateOnServer $ActivationPreference.Key.Name -confirm:$False 
    Below is what i am getting.

    What is your question?  Are you pointing out the yellow text?  This is normal, and appears every time EMS is opened.
    I should also point out that Microsoft provides a script to re-balance databases, if that's what you're trying to accomplish:
    You can use the RedistributeActiveDatabases.ps1 script to balance the active mailbox databases copies across a DAG. This script moves databases between their copies in an attempt to have an equal number of mounted databases on each server in DAG. If required,
    the script also attempts to balance active databases across sites.
    https://technet.microsoft.com/en-us/library/dd335158(v=exchg.141).aspx
    Mike Crowley | MVP
    My Blog --
    Baseline Technologies

  • How to run a batch file as windows Nt service

    Hi friends
    I want to know how to run a batch file as windows NT service.
    I got some information in the following link
    http://support.microsoft.com/kb/q243486/
    I tried it but i want to know what we need to include in Autoexnt.bat
    And one thing i need Instexnt.exe file. I cannot find tht file.
    Please search tht file and send me tht file or else send the link in which this file is present
    Please give me reply fast.its very urgent.
    Thanks in advance.

    Hi,
    My aim is to run a MS-DOS Batch file, that I created to run a Java Prgram.
    I need to call the Batch File from the Oracle Procedure, Also I may need to change the content of the Batch File (Argument to the Java JAR File ).
    I can keep the JAR FIle either in the Oracle Server or in the Application Server.
    The Java program is to convert XML Format FIle to PDF and MS Word format.
    Oracle Version : 10g 2.0.1.0.
    Thanks in advance
    Rizly

  • How to call java script function from JSP ?

    how to call java script function from JSP ?

    i have function created by java script lets say x and i want to call this function from jsp scriplet tag which is at the same page ..thanks

  • Passing parameters with spaces to SCCM Run PowerShell Script task

    I am working on an OS deployment task sequence in SCCM 2012 R2 with several Run PowerShell Script tasks.  Most of them run fine, but I am having trouble with the one I need to pass parameters to.
    The parameters I need to pass are:
    -ComputerOU "ou=All Workstations,dc=contoso,dc=com" -GroupDN "cn=Group1,ou=All Groups,dc=contoso,dc=com"
    I have that line (with actual DNs) entered in Parameters of the task.
    But when the script runs on the target machine, the values of the parameters in the script are truncated at the spaces.  $ComputerOU is set to "ou=All" and $GroupDN is set to "cn=Group1,ou=all"
    What syntax should I be using the Parameters field of the Task in order to properly pass PowerShell parameter string values that include spaces?
    Tim Curwick
    MadWithPowerShell.com

    Thank you, TC, but I am not calling the parameters from within PowerShell.
    The parameters are in the settings of a task sequence task to be used by the task to launch a script.  The syntax I am using would be correct for use within PowerShell or from a command line or batch script, but SCCM appears to be doing some parsing
    before or while it is passing them to the script, possibly dropping the quotes which causes mishandling of the spaces in the string values.
    Historically, it is always challenging to give one application parameters to pass to another application, and the required syntax can get quite tricky when the two application handle quotes or spaces differently, or when the parent application wants to parse
    something intended to be passed on as is to the child application.
    I'm sure someone has already figured out what the syntax needs to be for doing this with an SCCM 'Run PowerShell Script" task, it's just one of those issues that is hard to Google effectively.
    Any other ideas?
    Tim Curwick
    MadWithPowerShell.com

  • How to run a script from Calculation Manager

    Hi All,
    I would like to know how to run a script made by using Calculation Manager. I have converted a simple rule script which has just one statement(HS.EXP "A#Sales = 100") in "Sub Calculate()" by using FMRulesMigrator.exe and then imported, deployed to an application. when I execute "Calculate" from a Data Grid, the rule didn't take effect to application data. If I load the script by using classic rule editor, it works fine.
    Is there anything I have to know to run a rule script which is made by using Calculation Manager?
    Thanks in advance.
    CY.

    Hi,
    Refer the following the link for calling logic from new custom buttons using VBA.
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/f085dd92-a40c-2c10-dcb1-a7c24476b23a
    hpe this ll help.
    thnks.

Maybe you are looking for