如何用PowerShell脚本通过AWS SSM在EC2实例执行命令并获取校验值
实现方案
你当前用的aws ssm start-session是交互式会话模式,无法直接在本地脚本中获取远程命令的执行结果。要实现远程执行Get-FileHash并取回校验值,推荐以下两种非交互式方法:
方法1:使用aws ssm send-command(适合需跟踪命令状态的场景)
该命令可向EC2实例发送PowerShell命令,后续通过命令ID查询执行结果:
$instanceId = "i-xxxxxxxxx" $profile = "xxxxxxxx" # 注意:这里填EC2实例上的绝对路径,Windows实例用C:\开头 $filePath = "C:\path\to\file" # 发送PowerShell命令到EC2实例 $commandId = aws ssm send-command ` --targets "Key=instanceids,Values=$instanceId" ` --document-name "AWS-RunPowerShellScript" ` --parameters "commands=['Get-FileHash -Path `"$filePath`" -Algorithm SHA256 | Select-Object -ExpandProperty Hash']" ` --profile $profile ` --query "Command.CommandId" ` --output text # 等待命令执行完成(文件越大,等待时间需越长,可根据实际调整) Start-Sleep -Seconds 5 # 获取命令执行结果 $hashResult = aws ssm get-command-invocation ` --command-id $commandId ` --instance-id $instanceId ` --profile $profile ` --query "StandardOutputContent" ` --output text Write-Host "文件SHA256校验值:$hashResult"
关键说明:
- 用
AWS-RunPowerShellScript这个SSM官方文档,专门用于Windows实例执行PowerShell命令 - 通过
Select-Object -ExpandProperty Hash只提取哈希值,避免返回多余格式内容 - 如果文件过大,可替换固定等待为循环检查命令状态(用
aws ssm list-command-invocations查询Status字段)
方法2:使用aws ssm start-session命令模式(更简洁,需AWS CLI v2.3.0+)
直接通过Session Manager执行命令并返回结果,无需额外查询步骤:
$instanceId = "i-xxxxxxxxx" $profile = "xxxxxxxx" $filePath = "C:\path\to\file" # 直接执行远程命令并获取哈希值 $hashResult = aws ssm start-session ` --target $instanceId ` --profile $profile ` --document-name "AWS-RunPowerShellScript" ` --parameters "commands=['Get-FileHash -Path `"$filePath`" -Algorithm SHA256 | Select-Object -ExpandProperty Hash']" ` --output text Write-Host "文件SHA256校验值:$hashResult"
注意事项:
- 确保EC2实例已安装并运行SSM Agent(Windows实例默认预装,可通过
Get-Service AmazonSSMAgent检查状态) - 实例需拥有
AmazonSSMManagedInstanceCore权限策略,否则无法被SSM管理 - 远程文件路径必须是EC2实例上的有效绝对路径,避免使用相对路径
- 命令中的引号需正确转义,防止解析错误
内容的提问来源于stack exchange,提问作者Kamal
相关产品推荐
相关产品推荐

