windows update 3

User avatar
daniel
Site Admin
Posts: 223
Joined: Tue Jan 09, 2007 9:54 pm
Contact:

windows update 3

Postby daniel » Wed May 15, 2019 12:41 pm

[cmdletbinding()]
param (
[string]$ComputerName = $env:computername
)

write-host $ComputerName

$Session = Get-PSSession | where { $_.ComputerName -eq $ComputerName -and $_.State -eq 'Opened' }
if (-not $Session) {
try { $Session = New-PSSession -ComputerName $ComputerName -EA 1 } catch { throw }
}

Invoke-Command -Session $Session -ScriptBlock {
#Get Date
$DateAndTime = (Get-Date -format ddMMMyyyy-HH.mm)
#Register Scheduled Task with Date
Unregister-ScheduledJob -Name "InstallUpdates*"
Register-ScheduledJob -Name "InstallUpdates $DateAndTime" -RunNow -ScriptBlock {
$LogFile='C:\hpe\04-Install-Updates.log'
Add-content $LogFile -value ("--Start--" + (Get-Date));`
Add-content $LogFile 'Comments: ResultCode is 2 = Succeeded, 3 = Succeeded with Errors, 4 = Failed, 5 = Aborted'
$Criteria = "IsInstalled=0 and Type='Software'";`
$Searcher = New-Object -ComObject Microsoft.Update.Searcher;`
$SearchResult = $Searcher.Search($Criteria).Updates;`
Add-content $LogFile -value ('Search=' + $SearchResult.Count);`
$Session = New-Object -ComObject Microsoft.Update.Session;`
$Downloader = $Session.CreateUpdateDownloader();`
$Downloader.Updates = $SearchResult;`
$Downloader.Download();`
Add-content $LogFile -value ('Download=' + $Downloader.Updates.Count + ' ResultCode=' + $Downloader.Download().ResultCode);`
$Installer = New-Object -ComObject Microsoft.Update.Installer;`
$Installer.Updates = $SearchResult;`
$Result = $Installer.Install();`
Add-content $LogFile -value ('Installer=' + $Installer.Updates.Count + ' ResultCode=' + $Result.ResultCode + ' RebootRequired=' + $Result.RebootRequired);`
If ($Result.rebootRequired) { Add-content $LogFile 'Restart required.' };`
If ($Result.rebootRequired) { shutdown.exe /t 5 /r /f };`
Add-content $LogFile -value ("--End--" + (Get-Date));`

} #End scheduledjob scriptblock
} #End Invoke Scriptlock

Remove-PSSession -Session $Session

Return to “PowerShell”

Who is online

Users browsing this forum: No registered users and 1 guest