如何修改PowerShell脚本获取多远程服务器90天内到期证书名称
修改PowerShell脚本获取多台远程服务器90天内到期的证书名称
前提条件
- 目标远程服务器已开启WinRM服务(可通过
Enable-PSRemoting -Force在目标机器上配置) - 执行脚本的账号拥有目标服务器的管理员权限
修改后的完整脚本
# 定义需要检查的远程服务器列表(填入服务器名称或IP) $remoteServers = @( "Server01", "Server02", "192.168.1.100" ) # 定义要检查的证书存储路径 $certPaths = @( "Cert:\LocalMachine\My" ) # 计算90天后的日期作为到期阈值 $expiryThreshold = (Get-Date).AddDays(90) # 远程执行证书检查并收集结果 $expiringCertificates = Invoke-Command -ComputerName $remoteServers -ScriptBlock { param($certPaths, $expiryThreshold) $currentServer = $env:COMPUTERNAME $results = @() foreach ($certPath in $certPaths) { $certificates = Get-ChildItem -Path $certPath -ErrorAction SilentlyContinue foreach ($cert in $certificates) { # 筛选出未来90天内到期的证书 if ($cert.NotAfter -gt (Get-Date) -and $cert.NotAfter -lt $expiryThreshold) { $results += [PSCustomObject]@{ ServerName = $currentServer CertificateName = $cert.Subject # 证书主题作为名称,也可替换为$cert.FriendlyName ExpiryDate = $cert.NotAfter.ToString("yyyy-MM-dd HH:mm:ss") Thumbprint = $cert.Thumbprint } } } } return $results } -ArgumentList $certPaths, $expiryThreshold # 输出结果 if ($expiringCertificates) { Write-Host "以下是90天内到期的证书信息:" $expiringCertificates | Format-Table -AutoSize } else { Write-Host "未发现90天内到期的证书。" }
关键修改说明
- 添加远程服务器列表:通过
$remoteServers数组指定所有需要检查的目标机器 - 远程执行逻辑:使用
Invoke-Command在每台远程服务器上运行证书检查脚本,避免本地处理远程证书存储的权限问题 - 输出详细信息:返回包含服务器名称、证书名称、到期时间、指纹的结构化对象,方便查看和后续处理
- 错误处理:添加
-ErrorAction SilentlyContinue避免因证书存储路径不存在导致脚本中断
内容的提问来源于stack exchange,提问作者Sushmitha shetty
相关产品推荐
相关产品推荐

