# aardio 范例: Windows 自动更新接口



```aardio
// Windows 自动更新接口
// Windows Update Agent (WUA) COM API

import com;
import sys.qfe;
import console; 

//快速查看指定补丁是否安装
console.dump(sys.qfe("KB5132061"));

// 1. 创建 UpdateSession 实例
var session = com.CreateObject("Microsoft.Update.Session");

// 2. 创建搜索器并检索未安装的软件更新
var searcher = session.CreateUpdateSearcher();

console.showLoading("正在搜索可用更新...");
var  searchResult = searcher.Search("IsInstalled=0 and Type='Software'");

var updatesToInstall = com.CreateObject("Microsoft.Update.UpdateColl");

// 3. 过滤出指定的 KB 补丁
for index,update in com.each(searchResult.Updates) {
	
	for(i,kb in com.each(update.KBArticleIDs)){
		
		if(kb==="KB......"){
			console.log("找到未安装的补丁：",kb)
			
			if (!update.EulaAccepted) update.AcceptEula(); 
			updatesToInstall.Add(update);			
		}
	}
} 

// 4. 自动下载补丁
if(updatesToInstall.Count){
	console.showLoading("正在下载补丁...");	
	var downloader = session.CreateUpdateDownloader();
	downloader.Updates = updatesToInstall;
	
	var downloadResult = downloader.Download();
	console.log("下载状态码:",downloadResult.ResultCode);
	
	// 5. 静默安装补丁
	console.showLoading("正在安装补丁...");
	var installer = session.CreateUpdateInstaller();
	
	installer.Updates = updatesToInstall;
	var installResult = installer.Install();	
	
	console.log("安装结果代码: ",installResult.ResultCode);
	console.log("是否需要重启: ",installResult.RebootRequired);
}

console.pause();

```

