Ansible win_shell/win_command输出服务器标识而非命令结果求助
问题场景
使用Ansible的win_shell模块执行PowerShell命令,意图获取指定目录下的.ps1文件列表:
- name: get Ps1 files win_shell: get-ChildItem -path $testFolder -Filter *.ps1 -Recurse -File -Name -Depth 0 register: ps1_files args: executable: powershell
该命令在服务器本地PowerShell中执行正常,但Ansible返回的输出并非预期的文件列表,而是服务器标识信息:
"msg": { "changed": true, "cmd": "get-ChildItem -path $realProcessesFolder -Filter *.ps1 -Recurse -File -Name -Depth 0", "delta": "0:00:00.954839", "end": "2022-12-22 07:30:46.385668", "failed": false, "rc": 0, "start": "2022-12-22 07:30:45.430828", "stderr": "", "stderr_lines": [], "stdout": "\r\n\r\nComputerName : SL143312\r\nBuilddate : 2019-Aug-26 13:43:8\r\nProfile : Standard Application Server\r\nOS : Windows Server 2016 Standard Edition\r\nMachineType : VMware Virtual Platform\r\nModel : VMware, Inc.\r\nServerAppCode : TVP0\r\n\r\n\r\n\r\n", "stdout_lines": [ "", "", "ComputerName : SL143312", "Builddate : 2019-Aug-26 13:43:8", "Profile : Standard Application Server", "OS : Windows Server 2016 Standard Edition", "MachineType : VMware Virtual Platform", "Model : VMware, Inc.", "ServerAppCode : TT00", "", "", "" ] }
改用win_command模块并添加-nologo参数后,结果依旧异常:
win_command: powershell -noninteractive -nologo -command "get-ChildItem -path $env:realProcessesFolder -Filter *.ps1 -Recurse -File -Name -Depth 0"
问题根源
目标服务器的PowerShell配置文件(profile.ps1)在每次会话启动时自动执行了输出服务器标识信息的脚本,Ansible启动的PowerShell会话默认会加载该配置文件,导致额外输出干扰了命令的预期结果。
解决建议
跳过PowerShell配置文件加载
在执行命令时添加-NoProfile参数,阻止加载任何PowerShell配置文件,避免额外输出:
用win_shell模块的写法:- name: Get Ps1 files win_shell: get-ChildItem -path $testFolder -Filter *.ps1 -Recurse -File -Name -Depth 0 register: ps1_files args: executable: powershell -NoProfile用
win_command模块的写法:- name: Get Ps1 files win_command: powershell -NoProfile -NonInteractive -Command "Get-ChildItem -Path $env:realProcessesFolder -Filter *.ps1 -Recurse -File -Name -Depth 0"使用Ansible原生模块替代
优先使用Ansible专门的win_find模块查找文件,更符合Ansible最佳实践,且无需处理PowerShell配置干扰:- name: Get Ps1 files win_find: paths: "{{ testFolder }}" patterns: "*.ps1" recurse: no # 对应原命令的-Depth 0,不递归子目录 file_type: file register: ps1_files执行后可通过
ps1_files.files获取文件列表,每个元素包含name、path等详细字段。调整目标服务器PowerShell配置
若允许修改目标服务器,可通过$PROFILE变量定位PowerShell配置文件,移除其中输出服务器标识的代码。此方法会影响所有PowerShell会话,需谨慎操作。
内容的提问来源于stack exchange,提问作者Codrin
相关产品推荐
相关产品推荐

