You use the New-CredentialStoreItem to enter the credentials under which the scheduled script will connect to the vCenter.
This will allow you to connect to the vCenter without providing credentials.
Note that you need to do this with the same account under which you will run the Scheduled Task!
The script itself doesn't need a lot of changes.
This should do
Get-Module -Name VMware* -ListAvailable | Import-Module
Connect-VIServer -Server 'YourvCenter'
$head = @"
"@
$body = Get-Datastore |
Select @{N='Datastore';E={$_.Name}},
@{N='CapacityGB';E={[math]::Round($_.CapacityGB,1)}},
@{N='FreeSpaceGB';E={[math]::Round($_.FreeSpaceGB,1)}},
@{N='UsedPercent';E={[math]::Round(($_.CapacityGB - $_.FreeSpaceGB)/$_.CapacityGB*100,1)}},
@{N='FreePercent';E={
$p = [math]::Round((1 - ($_.CapacityGB - $_.FreeSpaceGB)/$_.CapacityGB)*100,1)
if($p -lt 10){"#br#$($p)"}
elseif($p -lt 30){"#by#$($p)"}
else{"#bg#$($p)"}
}} |
Sort-Object -Property UsedPercent -Descending |
ConvertTo-Html -Head $head
$body = $body.Replace('>#br#',' bgcolor="red">').Replace('>#by#',' bgcolor="yellow">').Replace('>#bg#',' bgcolor="green">')
$sMail = @{
To = 'vijay.venkatachalam@test.com'
From = 'vijay.venkatachalam@test.com'
Subject = 'Datastore Report'
BodyAsHtml = $true
Body = $body | Out-String
SmtpServer = 'owa.test.com'
}
Send-MailMessage @sMail
Disconnect-VIServer -Server 'YourvCenter' -Confirm:$false
And finally you create the Scheduled Task.
You can do this through the Task Scheduler GUI, or via a script.
$script = 'C:\yourscript.ps1'
$user = 'your_account'
$pswd = 'your_password'
$date = Get-Date (([datetime](Get-Date -Format g)).AddDays($_))-Format d
$sAction = @{
Execute = "powershell.exe"
Argument = "-NonInteractive -NoLogo -NoProfile -ExecutionPolicy Bypass $($script)"
}
$Action = New-ScheduledTaskAction @sAction
$interval = New-TimeSpan -Days 1
$repetetion_timespan = New-TimeSpan -Days 1
$sTrigger = @{
Once = $true
At = "$($date) 9:00am"
RepetitionInterval = $interval
RepetitionDuration = $repetetion_timespan
}
$Trigger = New-JobTrigger @sTrigger
$sTask = @{
TaskName = 'Daily Datastore Report'
User = $user
Password = $pswd
RunLevel = 'Highest'
Action = $Action
Trigger = $Trigger
}
Register-ScheduledTask @sTask