0

I have a PowerShell script as follows:

$ListOfServers = "Server1", "Server2"

$RunDefrag =   
{
    param($Server)
    $Volume = Get-WmiObject -Class Win32_Volume -ComputerName $Server -Filter "DriveLetter = 'c:'"

    $Result = $Volume.Defrag($False)

    if ($Result.ReturnValue -eq 0)
        { Write-Host "Defrag on $Server successful." }
    else
        { Write-Host "Defrag failed. Result code: " $Result.ReturnValue }
}

$ListOfServers | ForEach {Start-Job -ScriptBlock $RunDefrag -ArgumentList $_}

This runs fine when executed manually as a PowerShell script from my machine (with Administrative rights).

My problem is when I try and set the task up as a Scheduled Task. Here are my basic settings:

Actions: Start a program.
Details: powershell "& \"C:\PowerShell Scripts\Defrag.ps1"

I have played around with various settings for the task details, but nothing works for me. The task Runs, but the defrag does not start on the servers.

If anyone has any ideas, I'd be grateful.

The Woo
  • 569
  • 6
  • 20
  • 39
  • 1
    Assuming Windows Server 2008 or later, why not just use the Disk Defrag utility to schedule a defrag? It will create a scheduled task based on your selections. – joeqwerty Oct 09 '14 at 23:07
  • 1
    @joeqwerty The idea of having to do that to 300 servers. Better to create a PowerShell script to set up the scheduled tasks (rather than just running defrag directly). – Michael Hampton Oct 09 '14 at 23:24
  • What account is configured to launch this task? Did you configure it to use an administrator level account? – theterribletrivium Oct 09 '14 at 23:54
  • The account does have admin privileges on the servers, yes. I'd like to set this up as a task on one machine, as the list of servers affected will change (in the future I'd like to get it to run an AD check against our AD and run for specific servers). – The Woo Oct 10 '14 at 00:52
  • Why not schedule it once, and then import it to the other machines using a script? https://social.technet.microsoft.com/Forums/windowsserver/en-US/34517e40-a827-41b2-b361-254894d80404/import-scheduled-task-with-powershell?forum=winserverpowershell – MagnaVis Oct 10 '14 at 01:52
  • You might consider Group Policy: http://www.techrepublic.com/blog/the-enterprise-cloud/create-a-defragmentation-scheduled-task-in-windows-server-2008/ – Davidw Oct 10 '14 at 02:14

0 Answers0