Unable to Configure a PowerShell Script to Run as a Scheduled Task

Hi ,
I have a powershell script from Dieters blog http://scug.be/dieter/2011/07/06/scom-2007-how-to-backup-your-unsealed-management-packs/#comment-1058 which backups the unsealed management packs in SCOM. I am able to run the script successfully in the powershell
prompt but when i schedule it as a task it fails with an error code 1.
"Task Scheduler successfully completed task "\Backup Unsealed Management Pack" , instance "{xxxxxxxxxxxxxxxxxxxxxxxxxxxx}" , action "Powershell.exe" with return
code 1."
I am running the task using the highest privilages and have tried bypassing the script using and have configured the script as per http://www.metalogix.com/help/Content%20Matrix%20Console/SharePoint%20Edition/002_HowTo/004_SharePointActions/012_SchedulingPowerShell.htm
-ExecutionPolicy Bypass c:\scripts\myscript.ps1
Still i am unable to run the task without errors. Kindly assist.
Jesty

Hi Jesty,
Please make sure you have followed these steps to schedule a powershell script task:
1.  Save the powershell script as .ps1 in local computer.
2.  Right click the .ps1 file and run with powershell and check if the script can run successfully.
3.  schedule task->action:Start a program->Program/script:powershell.exe->Add argument:-ExecutionPolicy Bypass c:\scripts\myscript.ps1
Best Regards,
Anna

Similar Messages

  • Workflow does not start when PowerShell Script is run from Task Scheduler

    I have a PS script that updates an item in a SP2010 list so that a workflow will be started.  When I run the PS script manually from the PS window on the server it resides, the script runs flawlessly.  If I set a scheduled task on the same server
    to run the script with the same credentials as are being used in the PS window, the script runs, updated the info on the list, but DOES NOT start the workflow.  As we know, SPD workflows cannot be started by anonymous or system accounts.  It is as
    if the task scheduler adds a bit of information that makes the SP2010 list think the information was updated by one of these accounts even though the field in the list for the item being updated shows the correct account.
    HELP!!!
    D

    Hi,
    The issue might be related to the script or schedule task settings your configured. You’d better check the settings.
    For example, which option do you set to run the scheduled task? You may select “Run whether user is logged on or not” instead of “run only when user is logged on” as shown in this article:
    http://blog.pointbeyond.com/2010/04/23/run-powershell-script-using-windows-server-2008-task-scheduler/
    Hope it helps.
    Best Regards,
    Sally Tang

  • Does Forefront Endpoint Protection 2010 block powershell scripts from running?

    Hi all,
    I have a task that runs a Powershell script on a set schedule on a particular machine.  It has failed to run and I thought 1 of the potential reasons would be that FEP 2010 blocks the Powershell script from being run.  Does FEP 2010 do that?  If so, where can I find the setting to allow Powershell scripts (or VB scripts or Java scripts) to be run by my task?
    Thanks for your help in advance.
    Howard Lee - Microsoft

    If the script detect as malicious , FEP will block it, otherwise it won't block normal and safe PowerShell scripts. You may take a look at event viewer and see whether it being blocked or detect as malicious code by FEP or not.

  • Powershell script not running in the task scheduler...

    I've created a .ps1 script to transfer a file using WinSCP can run it in the ISE environment, in the PS window, and with the run command. I've transferred the command I used in the run prompt to the task scheduler but it is not running. It is running everywhere
    else just not in the scheduler. It says that it completes okay and gives a return code of OpCode=2
    The action is set to run this: c:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
    The Arguments: -ExecutionPolicy Bypass -file "C:\Users\me\scriptsWCP\FileTransferPS.ps1"
    Also have it running with the highest permission and as SYSTEM

    Hi,
    To run a powershell script with parameters in the Task Scheduler:
    Program: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Add argument (optional): -Command "& c:\scripts\test.ps1 -par1 2 -par2 3"
    Hope the below two articles be helpful for you:
    Schedule PowerShell Scripts that Require Input Values
    https://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/schedule-powershell-scripts-that-require-input-values.aspx
    How to Schedule a PowerShell Script
    http://dmitrysotnikov.wordpress.com/2011/02/03/how-to-schedule-a-powershell-script/
    Regards,
    Yan Li
    Regards, Yan Li

  • Creating Powershell script to run against Multiple XML Files: Correcting Nordic characters. Renaming only the files that were corrected.

    Greetings,
    I am new to powershell and scripting and would like to create a powershell script to do the following to XML files.
    I would like to change the data received in XML files that contains special Nordic characters: such as 
    ä, Ä, é, ö, Ö, ü, Ü, and ß respectfully.
    The file names that gets drop to me come in with the following naming convention: C54ABC_111120140500_1, C54ABC_111120140500_2, C54ABC_111120140500_3, C54ABC_111120140500_4 all the way to C54ABC_111120140500_12.
    By automating the script, I would like the script to look into a directory containing these files and access the data within it and change the the data that has the special characters to the English Dictionary character equivalent.
    e.g. ä for a, Ä for A, é for e, ö for o, Ö for O, ü for u, Ü for U, and ß for ss.
    Once that step is complete. I would like to rename the file from C54ABC_111120140500_1.xml to C54ABC_111120140500_1_rctf.xml (adding an additional 5 characters to the end of a file that was corrected) if the file did not need any correction then renaming is
    not needed.
    the working directory (Source and destination) will remain in the same location. e.g. C:\Temp\
    Currently I was able to come up with the following, however I am stuck when it comes to the renaming part since, it requires "IF and Else" statments .... I think.
    $Source = "C:\Temp"
    $Destination = "C:\Temp"
    $regex33 = "\*.xml"
    (Get-Content $regex33) |
    ForEach-Object {$_ -replace "ä", "a" -replace "Ä", "A" -replace "é", "e" -replace "ö", "o" -replace "Ö", "O" -replace "ü", "u" -replace "Ü", "U" -replace "ß", "ss"}
    #Rename-Item -NewName {$_.name -replace -whatif}
    Your Assistance and Expertise is greatly appreciated.
    Thank you in advance KC.

    Hi KC
    You could try something like this.
    Let me know how you get on and if you've any questionds.
    cheers, Tim
    $Source = 'C:\Temp'
    Set-Location $source
    $xmlFiles = Get-ChildItem -Path $source -Filter *.xml
    ForEach ($xmlFile in $xmlFiles)
      $content = Get-Content -Path $xmlFile.FullName
      $renameFile = $false
      Switch -Wildcard ($content) {
        '*ä*'
          $renameFile = $true
          $content = $content -creplace 'ä', 'a'
        '*Ä*'
          $renameFile = $true
          $content = $content -creplace 'Ä', 'A'
        '*é*'
          $renameFile = $true
          $content = $content -creplace 'é', 'e'
        '*ö*'
          $renameFile = $true
          $content = $content -creplace 'ö', 'o'
        '*Ö*'
          $renameFile = $true
          $content = $content -creplace 'Ö', 'O'
        '*ü*'
          $renameFile = $true
          $content = $content -creplace 'ü', 'u'
        '*Ü*'
          $renameFile = $true
          $content = $content -creplace 'Ü', 'U'
        '*ß*'
          $renameFile = $true
          $content = $content -creplace 'ß', 'ss'
      If ($renameFile)
        $newFileName = "$($xmlFile.BaseName)_rctf.xml"
        $content | Out-File -FilePath $xmlFile.FullName -Force
        Rename-Item -Path $xmlFile.PSChildName -NewName $newFileName

  • Batch File Won't Run as a Scheduled Task

    I have two batch files that won't run as scheduled tasks but run perfectly fine when I double-click them.
    I've already set them to run with highest privileges, the account running them is an administrator account, that account has full permissions to the folder and file. I've checked every thread I could find but they simply won't run. No error, no log, nothing...
    If I right click the scheduled task and select Run, nothing happens.
    Any ideas?

    Hi,
    As far as I know, you have to enter the script folder in the "Start in" field. Else it just won't work - and won't really give you any meaningful error messages. So, please check your setting.
    Roger Lu
    TechNet Community Support

  • Trying to run a Powershell script to run an executable

    When I run this line, the script works fine:
    cmd /C '"c:/Program Files/SolarWinds/WakeOnLine.exe" -IP (a IP address) -MAC (A Mac Address)'
    When I run this line with variables I doesn't work.  It's something with the variables that's not working and I just can't figure it out.
    $IPVar=(a IP address)
    $MACVar=(A Mac Address)
    cmd /C '"c:/Program Files/SolarWinds/WakeOnLine.exe" -IP $IPVar -MAC $MACVar'
    Please help.
    Thanks.

    Hi,
    Surrounding the command in single quotes won't allow the variables to expand. Try it with double quotes only:
    $IPVar = '1.2.3.4'
    $MACVar = 'AB-CD-EF-01-02-03'
    Write-Host '"c:/Program Files/SolarWinds/WakeOnLine.exe" -IP $IPVar -MAC $MACVar'
    Write-Host "C:\Program Files\SolarWinds\WakeOnLine.exe -IP $IPVar -MAC $MACVar"
    You can also look at using Start-Process and -ArgumentList if that doesn't work:
    http://technet.microsoft.com/en-us/library/hh849848.aspx
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • Help sought getting powershell script to run

    Platform is SP 2010 service pack 2.
    Goal is to generate a list of users within the farm that are no longer in active directory.
    http://sharepointpsscripts.codeplex.com/releases/view/21699  is a script that purports to accomplish this.
    However, what I am seeing is a script that has executed for more than 12 hours, with the only output being sent to the console and consisting of logins and the error:
    FindAll : Exception calling "FindAll" with "0" argument(s): "A referral was returned from
    the server.
    At C:\Users\sa_spfarm\desktop\check-sporphans.ps1:20 char:36
    +     $colResults = $objSearcher.FindAll <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException
    I am logged into a farm server as the farm admin account. 
    The bit of code that is failing is:
    function Check_User_In_ActiveDirectory([string]$LoginName, [string]$domaincnx)
    $returnValue = $false
    #Filter on User which exists and activated
    #$strFilter = "(&(objectCategory=user)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(samAccountName=$LoginName))"
    #Filter on User which only exists
    #$strFilter = "(&(objectCategory=user)(objectClass=user)(samAccountName=$LoginName))"
    #Filter on User and NTgroups which only exists
    $strFilter = "(&(|(objectCategory=user)(objectCategory=group))(samAccountName=$LoginName))"
    $objDomain = New-Object System.DirectoryServices.DirectoryEntry($domaincnx)
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"
    #$objSearcher.PropertiesToLoad.Add("name")
    $colResults = $objSearcher.FindAll()
    if($colResults.Count -gt 0)
    #Write-Host "Account exists and Active: ", $LoginName
    $returnValue = $true
    return $returnValue
    This function is called by another which is called by another. The code came from the URL above.
    What output is occurring other than the error is a string of write-host cmdlets that are listing some logins that used to exist on the farm. 
    I am thinking that iif there is no error trapping - and I don't see anything obviously trapping errors - and the login is no longer in active directory (the whole purpose of the script) then the attempt to perform the findall would fail, and perhaps raise
    the above error?
    What happens to the program flow at that point?
    Does findall return a 0?  That seems to be what the code is expecting?  But if that were the case, then when this function returns, the function which calls it looks at the 0 return code and compares it to $False. If the return code is equal to
    $False, then the write-output occurs.
    I am trying to figure out how to tweak the script so that I actually get results output.
    Thanks for any ideas you might be able to suggest.

    What's the format of the domain that you're using in the script?
    This post is my own opinion and does not necessarily reflect the opinion or view of Slalom.

  • Failing to start a powershell scripts from Start/Run

    So my real goal is to get a script that we've written to run in a scheduled task. Based on one of the early Scripting Guys blogs, I am working with Start/Run to get the syntax down.
    Here's what I am trying to do is run the command, capturing any output it produces into a log file for later examination.
    So I write
    powershell –noexit –command &{ "H:\Temp\user information\Data\Data\User Update.ps1" >> H:\temp\Data\Data\Runlog.txt}
    When I try to run this in Start/Run, I get this:
    H:\Temp\user : The term 'H:\Temp\user' is not recognized as the name of a
    cmdlet, function, script file, or operable program. Check the spelling of the
    name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:4
    + &{ H:\Temp\user information\Data\Data\User Update.ps1
    >>H:\tem ...
    +    ~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (H:\Temp\user:String) [], Comman
       dNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    I tried to quote it as described in another of the scripting guys blog - dragging the file from windows explorer into the start/run command line.
    What else am I missing here? 

    Hi,
    Use -File instead of -Command in the arguments section.
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

  • System.Drawing.Bitmap in a scheduled powershell script

    I've written a powershell script to date stamp multipage tiffs, but I check to make sure the file name follows the correct format before doing so. The file name must contain the date, sequence number, and number of pages. The script works fine when run manually,
    but when run from task scheduler it fails to query the number of pages in the TIFF. Any ideas why the .NET features wouldn't work from a powershell script run as a scheduled task?
    I am putting the page number in the variable "count" by doing the following:
     $i=[System.Drawing.Bitmap]::FromFile($file.Fullname);$i.GetFrameCount($i.FrameDimensionsList[0]) 
     $count=$i.GetFrameCount([System.Drawing.Imaging.FrameDimension]::Page)
    FULL SCRIPT FOLLOWS
    #Define the input and output folders and date format
    $Original_TIFFs="C:\scans"
    $Modified_TIFFs=";\\test\Shared\SDS\"
    $date = get-date -Format d
    $datename=Get-Date -format yyyyMMdd
    Set-Location $Original_TIFFs
    #Configure email settings
    $emailFrom = "removed"
    $emailTo = "removed"
    $smtpServer = "removed"
    $body = "Rename scanned claims file to the correct format. This email was sent from: ", $env:computername
    #Define the location of the TIFF command line executable and its parameters
    $200DLL='C:\TiffDLL200Commandline\Cmd200.exe '
    $arg1='"FILE='
    #Modify arg2 to put the output directory in front of the ; if don't want to overwrite current file
    #$arg2=';|OW=Yes|BITS=2|TEXT=2;Received Date: '
    $arg2=$modified_TIFFs
    $arg3=';|BITS=2|TEXT=2;Received Date: '
    $arg4='|TEXTOPS=-5;;10;14;"'
    $files=Get-ChildItem $Original_TIFFs -Filter *.tif
    if ($files -eq $null)
      $subject = "No files to process today, directory empty."
      $smtp = new-object Net.Mail.SmtpClient($smtpServer)
      $body = "No files were processed today. This email was sent from: ", $env:computername
      $smtp.Send($emailFrom, $emailTo, $subject, $body)
    else
    foreach ($file in $files)                                                                  
       #Begin loop to check each file and process
     #Loads subsystems for opening TIFFs and second line puts the number of images into variable
     $i=[System.Drawing.Bitmap]::FromFile($file.Fullname);$i.GetFrameCount($i.FrameDimensionsList[0]) 
     $count=$i.GetFrameCount([System.Drawing.Imaging.FrameDimension]::Page)
     #If statement checks if filename format is correct
     if ($file -match '^\d{8}\d{3}_H_S_\d+_\d{8}[.tif]{4}$')
      $file.name -match '^(?<date1>\d{8})\d{3}_H_S_(?<page_count>\d+)_(?<date2>\d{8})[.tif]{4}$'   #Regex to put tests in $matches to check against
      if (($matches.date1 -eq $datename) -and ($matches.date2 -eq $datename))                      #Check if filename contains correct date
      if ($count -eq $matches.page_count)                                                          #Check if filename
    contains the correct page count
       #insert TIFF modification
        $allargs=$200Dll+$arg1+$file+$arg2+$file+$arg3+$date+$arg4
        cmd /c $allargs
        #cmd /c xcopy $file \\test\shared\SDS                                                   #Deprecated because now having
    TIFF200DLL create a new file rather than overwrite
        $i.Dispose()                                                                  
                #Close file stream so file can be deleted: http://support.microsoft.com/kb/814675
        Remove-Item $file.Name
        #Next section is for a different output directory; Setup a seperate batch file to delete original TIFFs in the middle of the night
        <#
        $allargs="cmd200 "+$arg1+$file+";"+$Modified_TIFFs+";"+$arg2+$date+$arg3
        cmd /c $allargs
        #>
        else                                                                    
                     #else statement to send out error message if the number of pages differs from name
        $subject = "The number of pages in the file ", $file.FullName, "differs from the actual count of ", $count, ". File will not be sent, please correct before tomorrow for processing."
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body)
      }  #Close IF/THEN for correct date is in filename
     else
        $subject = "Date portion of filename is incorrect, please fix. File will not be sent to SDS", $file.FullName," ."
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body)
     }                                                    #Close IF/THEN for initial filename check
     else
        $subject = "File does not meet proper naming convention and will not be stamped nor sent to SDS", $file.FullName, " ."
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body)
    }                                                     #Close FOR loop
    }                                                     #Close Else for check if FILES=NULL

    You are buikding thisin the ISE?
    You need too add:
    add-type -AssemblyName System.Drawing
    ¯\_(ツ)_/¯

  • Can't access Modal dialog box via Powershell script

    Hi,
    I have a powershell script to login to an IE website and everything works fine excepting when I call a modal dialog box.  I've attached the line where the modula dialog is invoked.  When it gets to this part the script hangs and I'm unable
    to get past this.  I've googled a few articles where it suggests I should run an a scheduled task to scrape for the modal dialog box but I've tried it without much luck.  If you can please give me some pointers on resolving this issue. 
    Thnx
    Sue.
    $ie.Document.getElementsByTagName("button") | ? { $_.innerText -eq 'UNLOCK User' } | Select-Object -first 1 | % { $_.Click() }
    Sue

    Hi,
    I have a powershell script to login to an IE website and everything works fine excepting when I call a modal dialog box.  I've attached the line where the modula dialog is invoked.  When it gets to this part the script hangs and I'm unable
    to get past this.  I've googled a few articles where it suggests I should run an a scheduled task to scrape for the modal dialog box but I've tried it without much luck.  If you can please give me some pointers on resolving this issue. 
    Thnx
    Sue.
    $ie.Document.getElementsByTagName("button") | ? { $_.innerText -eq 'UNLOCK User' } | Select-Object -first 1 | % { $_.Click() }
    Sue

  • Powershell script to get the low disk space on the servers...

    Hi,
    We have many SQL & Sharepoint servers running on windows server. I need some Powershell script to get the low disk space on those servers and it should send an mail alert saying "Disc d:\ have less than threshold 15% free space".
    Awaiting for response.
    Thanks
    Anil

    you should be able to use this powershell script which you can run as a scheduled task.
    just change the details at the start of the script to point the script to the right location to create log files. you will need to have a plain text file containing a list of server names or ip addresses that you want to check drive space on.
    # Change the following variables based on your environment
    #specify the path to the file you want to generate containing drive space information
    $html_file_dir = "\\server\share\DriveSpace"
    #specify the path and file name of the text file containing the list of servers names you want to check drive space on - each server name on a seperate line in plain text file
    $server_file = "\\server\share\servers.txt"
    #speicfy the from address for the email
    $from_address = "[email protected]"
    #specify the to address for the email
    $to_address = "[email protected]"
    #specify the smtp server to use to send the email
    $email_gateway = "smtp.domain.com" # Can either be DNS name or IP address to SMTP server
    # The seventh line from the bottom (line 167) is used if your smtp gateway requires authentication. If you require smtp authentication
    # you must uncomment it and set the following variables.
    $smtp_user = ""
    $smtp_pass = ""
    # Change the following variables for the style of the report.
    $background_color = "rgb(140,166,193)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
    $server_name_font = "Arial"
    $server_name_font_size = "20px"
    $server_name_bg_color = "rgb(77,108,145)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
    $heading_font = "Arial"
    $heading_font_size = "14px"
    $heading_name_bg_color = "rgb(95,130,169)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
    $data_font = "Arial"
    $data_font_size = "11px"
    # Colors for space
    $very_low_space = "rgb(255,0,0)" # very low space equals anything in the MB
    $low_space = "rgb(251,251,0)" # low space is less then or equal to 10 GB
    $medium_space = "rgb(249,124,0)" # medium space is less then or equal to 100 GB
    #### NO CHANGES SHOULD BE MADE BELOW UNLESS YOU KNOW WHAT YOU ARE DOING
    # Define some variables
    $ErrorActionPreference = "SilentlyContinue"
    $date = Get-Date -UFormat "%Y%m%d"
    $html_file = New-Item -ItemType File -Path "$html_file_dir\DiskSpace_$date.html" -Force
    # Create the file
    $html_file
    # Function to be used to convert bytes to MB or GB or TB
    Function ConvertBytes {
    param($size)
    If ($size -lt 1MB) {
    $drive_size = $size / 1KB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' KB'
    }elseif ($size -lt 1GB){
    $drive_size = $size / 1MB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' MB'
    }ElseIf ($size -lt 1TB){
    $drive_size = $size / 1GB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' GB'
    }Else{
    $drive_size = $size / 1TB
    $drive_size = [Math]::Round($drive_size, 2)
    [string]$drive_size + ' TB'
    # Create the header and footer contents of the html page for output
    $html_header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Server Drive Space</title>
    <style type="text/css">
    .serverName { text-align:center; font-family:"' + $server_name_font + '"; font-size:' + $server_name_font_size + `
    '; font-weight:bold; background-color: ' + $server_name_bg_color + '; border: 1px solid black; width: 150px; }
    .headings { text-align:center; font-family:"' + $heading_font + '"; font-size:' + $heading_font_size + `
    '; font-weight:bold; background-color: ' + $heading_name_bg_color + '; border: 1px solid black; width: 150px; }
    .data { font-family:"' + $data_font + '"; font-size:' + $data_font_size + '; border: 1px solid black; width: 150px; }
    #dataTable { border: 1px solid black; border-collapse:collapse; }
    body { background-color: ' + $background_color + '; }
    #legend { border: 1px solid black; ; right:500px; top:10px; }
    </style>
    <script language="JavaScript" type="text/javascript">
    <!--
    function zxcWWHS(){
    if (document.all){
    zxcCur=''hand'';
    zxcWH=document.documentElement.clientHeight;
    zxcWW=document.documentElement.clientWidth;
    zxcWS=document.documentElement.scrollTop;
    if (zxcWH==0){
    zxcWS=document.body.scrollTop;
    zxcWH=document.body.clientHeight;
    zxcWW=document.body.clientWidth;
    else if (document.getElementById){
    zxcCur=''pointer'';
    zxcWH=window.innerHeight-15;
    zxcWW=window.innerWidth-15;
    zxcWS=window.pageYOffset;
    zxcWC=Math.round(zxcWW/2);
    return [zxcWW,zxcWH,zxcWS];
    window.onscroll=function(){
    var img=document.getElementById(''legend'');
    if (!document.all){ img.style.position=''fixed''; window.onscroll=null; return; }
    if (!img.pos){ img.pos=img.offsetTop; }
    img.style.top=(zxcWWHS()[2]+img.pos)+''px'';
    //-->
    </script>
    </head>
    <body>'
    $html_footer = '</body>
    </html>'
    # Start to create the reports file
    Add-Content $html_file $html_header
    # Retrieve the contents of the server.txt file, this file should contain either the
    # ip address or the host name of the machine on a single line. Loop through the file
    # and get the drive information.
    Get-Content $server_file |`
    ForEach-Object {
    # Get the hostname of the machine
    $hostname = Get-WmiObject -Impersonation Impersonate -ComputerName $_ -Query "SELECT Name From Win32_ComputerSystem"
    $name = $hostname.Name.ToUpper()
    Add-Content $html_file ('<Table id="dataTable"><tr><td colspan="3" class="serverName">' + $name + '</td></tr>
    <tr><td class="headings">Drive Letter</td><td class="headings">Total Size</td><td class="headings">Free Space</td></tr>')
    # Get the drives of the server
    $drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" -ComputerName $_ -Impersonation Impersonate
    # Now that I have all the drives, loop through and add to report
    ForEach ($drive in $drives) {
    $space_color = ""
    $free_space = $drive.FreeSpace
    $total_space = $drive.Size
    $percentage_free = $free_space / $total_space
    $percentage_free = $percentage_free * 100
    If ($percentage_free -le 5) {
    $space_color = $very_low_space
    }elseif ($percentage_free -le 10) {
    $space_color = $low_space
    }elseif ($percentage_free -le 15) {
    $space_color = $medium_space
    Add-Content $html_file ('<tr><td class="data">' + $drive.deviceid + '</td><td class="data">' + (ConvertBytes $drive.size) + `
    '</td><td class="data" bgcolor="' + $space_color + '">' + (ConvertBytes $drive.FreeSpace) + '</td></tr>')
    # Close the table
    Add-Content $html_file ('</table></br><div id="legend">
    <Table><tr><td style="font-size:12px">Less then or equal to 5 % free space</td><td bgcolor="' + $very_low_space + '" width="10px"></td></tr>
    <tr><td style="font-size:12px">Less then or equal to 10 % free space</td><td bgcolor="' + $low_space + '" width="10px"></td></tr>
    <tr><td style="font-size:12px">Less then or equal to 15 % free space</td><td bgcolor="' + $medium_space + '" width="10px"></td></tr>
    </table></div>')
    # End the reports file
    Add-Content $html_file $html_footer
    # Email the file
    $mail = New-Object System.Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($html_file)
    $mail.From = $from_address
    $mail.To.Add($to_address)
    $mail.Subject = "Server Diskspace $date"
    $mail.Body = "The diskspace report file is attached."
    $mail.Attachments.Add($att)
    $smtp = New-Object System.Net.Mail.SmtpClient($email_gateway)
    #$smtp.Credentials = New-Object System.Net.NetworkCredential($smtp_user,$smtp_pass)
    $smtp.Send($mail)
    $att.Dispose()
    # Delete the file
    Remove-Item $html_file
    Regards,
    Denis Cooper
    MCITP EA - MCT
    Help keep the forums tidy, if this has helped please mark it as an answer
    My Blog
    LinkedIn:

  • FIM Reporting ETLScript PowerShell Script for SCSM 2012?

    Hi,
    The FIM Reporting Deployment Guide is great, however on a few occasions it forgets to mention where you meant to execute things (http://technet.microsoft.com/en-us/library/jj133855(v=ws.10).aspx) .
    For example, if it wasn't for the screenshot in the article, we would not have known that we need to run the ETLScript from the FIM Service/Portal server.
    Everything until the ETLScript has thus far worked; and we have deployed the Service Manager 2012 console on the FIM Service/Portal server (since we are using SCSM 2012 for FIM Reporting).
    However, it appears that the ETLScript (in the deployment guide) has been written for SCSM 2010.
    So, has Microsoft or anyone published an updated SCSM 2012 ETLScript script?
    Thanks,
    SK

    Could this be it?
    http://gallery.technet.microsoft.com/PowerShell-Script-to-Run-a4a2081c

  • Powershell script in autostart folder

    Hello
    I put two scripts to alluser startupfolder C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
    a Batch file which shall start a powershell script.
    The result is not as expected: I want the powershell script to run but the script is opened by Notepad and displayed.
    1) How do I manage to run the script
    2) what is the reason for displaying the script
    thanks or help

    Hi,
    What's in the batch file?
    Also, take a look at the default action when you double click on a .ps1 file. That's on purpose.
    EDIT: Just to cut to the chase, use -File:
    http://ss64.com/ps/powershell.html
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Windows Server Backup scheduled task run successfully but backup do not start (not running) on Windows Server 2012

    Hi,
    A backup job has been setup on Windows Server 2012 (Platform: Win32NT; ServicePack: ; Version: 6.2.9200.0; VersionString : Microsoft Windows NT 6.2.9200.0) via Windows Backup Software UI (Local Backup 1.0).
    It is appearing as a scheduled task "\Microsoft\Windows\Backup\Microsoft-Windows-WindowsBackup" belonging to user 'nt authority\system' in task scheduler.
    The problem is that the Backup job never start despite the scheduled task running and completing successfully (when run automatically or manually)!
    Would you be able to explain why and assist in resolving that issue?
    Here is what we know:
    When the backup is run manually via the Windows Backup Software UI, it works fine.
    When the backup is run via command line (as set in schedule task) in a cmd command prompt (as local/domain 'administrator' or as 'nt authority\system' which is possible by running command prompt via 'PsExec.exe -i -s cmd'), something like "%windir%\System32\wbadmin.exe
    start backup -templateId:{f11eb3aa-74e7-4ff4-a57b-d8d567ee3f77} -quiet", it works fine.
    If you manually run the preset scheduled task while logged in as administrator, the task run and complete successfully but the backup job does not start.
    Idem if you schedule task is run automatically at scheduled time.
    The schedule task run and complete successfully but the backup job does not start.
    It is confirmed by running the following in a command prompt as 'nt authority\system':
    schtasks /run /tn "\Microsoft\Windows\Backup\Microsoft-Windows-WindowsBackup"
    SUCCESS: Attempted to run the scheduled task "\Microsoft\Windows\Backup\Microsoft-Windows-WindowsBackup".
    Despite success result, the Backup job does not start running...
    No errors or warning appears anywhere in Event Logs (Microsoft > Windows > Backup or Task Scheduler) nor in the scheduled task History tab. The schedule task complete successfully but no Backup job is run...
    If scheduled task automatically set by Windows Backup software is duplicated (copied) and set manually it runs fine as 'administrator' and as 'nt authority\system' (subject that 'nt authority\system' is added to the 'Backup Operators' AD group).
    Here is an export of the current pre-set schedule task, is there any settings that need to be changed to make it works?
    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
      <RegistrationInfo>
        <Author>MYDOMAIN\SERVER1</Author>
        <SecurityDescriptor>D:AR(A;OICI;GA;;;BA)(A;OICI;GR;;;BO)</SecurityDescriptor>
      </RegistrationInfo>
      <Triggers>
        <CalendarTrigger id="Trigger 1">
          <StartBoundary>2014-07-14T21:00:00</StartBoundary>
          <Enabled>true</Enabled>
          <ScheduleByDay>
            <DaysInterval>1</DaysInterval>
          </ScheduleByDay>
        </CalendarTrigger>
      </Triggers>
      <Principals>
        <Principal id="Author">
          <UserId>S-1-5-18</UserId>
          <RunLevel>HighestAvailable</RunLevel>
        </Principal>
      </Principals>
      <Settings>
        <MultipleInstancesPolicy>Parallel</MultipleInstancesPolicy>
        <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
        <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
        <AllowHardTerminate>true</AllowHardTerminate>
        <StartWhenAvailable>true</StartWhenAvailable>
        <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
        <IdleSettings>
          <StopOnIdleEnd>false</StopOnIdleEnd>
          <RestartOnIdle>false</RestartOnIdle>
        </IdleSettings>
        <AllowStartOnDemand>true</AllowStartOnDemand>
        <Enabled>true</Enabled>
        <Hidden>false</Hidden>
        <RunOnlyIfIdle>false</RunOnlyIfIdle>
        <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
        <UseUnifiedSchedulingEngine>false</UseUnifiedSchedulingEngine>
        <WakeToRun>false</WakeToRun>
        <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
        <Priority>7</Priority>
      </Settings>
      <Actions Context="Author">
        <Exec>
          <Command>%windir%\System32\wbadmin.exe</Command>
          <Arguments>start backup -templateId:{f11eb3aa-74e7-4ff4-a57b-d8d567ee3f77} -quiet</Arguments>
        </Exec>
      </Actions>
    </Task>
    Thank you in advance for your feedback.

    Once again, the issue is not to run the backup manually from the command line but to have it run via the scheduled task setup by the Windows Backup software.
    By default, the schedule task is to be run as NT Authority\System, and when run under this account, the backup does not start (even though account is member of Backup Operators) and job can manually be run via elevated command prompt. This is not a normal
    behavior and constitute a major bug in Windows Server 2012.
    From my understanding the NT Authority\System account is a built-in account from Windows that should by default be part of the Administrators group (built-in) even though it does not explicitly appears like it in AD by default.
    This account shall have by default Administrators rights and Backup Operators rights (via the Administrators group) without being explicitly added to those groups (http://msdn.microsoft.com/en-gb/library/windows/desktop/ms684190%28v=vs.85%29.aspx). By design
    it is supposed to be the most powerful account which has unrestricted access to all local system resources. If that is not the case (as it seems) then this would constitute a major bug in Windows Server 2012 edition.
    As said previously and as you confirmed, currently by default NT Authority\System on Windows 2012 server cannot start backup manually via an elevated command prompt unless it is manually added to Backup Operators (or Administrators) group. But wouldn't that
    constitute a bug of Windows Server 2012?
    Our server has not yet been restarted since I added NT Authority\System account to the Administrators group explicitly manually so I cannot yet confirmed it would sort the issue. Indeed it is heavily in use so cannot easily be restarted. Will confirm when
    done.
    We also have an additional problem where after a while of last reboot, part of the Exchange ECP can no longer be properly loaded in the web browser due to compilation error (compilation is done via NT Authority\System account which seems to no longer have
    sufficient right to compile .NET code). What is strange is that it works at first and then stop working at some point... I am hopeful that adding NT Authority\System to the Administrators group would sort this issue as well but once again, that shall not be
    needed!!!
    Could a Windows Server 2012 update introduced some security policy changes or else that prevent NT Authority\System to have full power?

Maybe you are looking for

  • How to clear invoices with different house banks

    Hi, i have posted 3 invoices to one vendor now i want to clear 2 invoices from one house bank ( citi bank) and 1 invoice from another house bbank (abn amro ) how can i make settings in fbzp ? thanks inadvance for ur answer points wil b assigned Regar

  • BIG IMESSAGE/TEXTING PROBLEMS

    After both my sister and I upgraded our iPhone 4 and iPhone 4S to iOS 7, when I text my sister now she receives the text message from my phone number and a separate text from her own phone number. I believe she is also receiving iMessages between me

  • Color correction - match two scenes

    Hello USING CS4 I posted this question earlier this week but got no response.  So I decided to repost with a link to the video. I need to more closely match the colors of the wall in this sample exceprt clip http://www.youtube.com/user/rowbyville?fea

  • Add plant wise details in fk10n

    Hi all, Is there any report or transaction code which displays Vendor account by Company Code and a specific plant. I know FK10n but it displays the Vendor account Balance for the Company Code and not for the Plant and Company Code. Please Advise.Tha

  • OS X Mavericks Crashes Every 15 minutes

    No problems until upgrade.  Now, the comptuer is useless.  Crash report below.  Any help greatly appreciate.... Anonymous UUID:       FF6EAA5F-53F9-B989-9082-D8FF81E1B5FE Sun Nov 24 09:38:06 2013 panic(cpu 1 caller 0xffffff800ef60f95): "hfs_getnewvno