如何使用ansible重命名/移动远程windows主机上的文件?

如何使用ansible重命名/移动远程windows主机上的文件?,ansible,Ansible,似乎有几种解决方案,它们都分为多个步骤,例如:。 *复制和删除 *使用本机wincommand或pwoershell 但是,难道不只是重命名为win_模块吗?或者选择“复制”以在复制后删除源?我找到了这个问题的一些答案: 首先要指出的是,这是针对远程windows主机的。对于Unix系统,我们已经在stackoverflow中找到了很多答案,而对于windows则不然 没有win_重命名模块,也没有带有重命名选项的win_文件。无法使用win_copy,因为该文件已在远程系统上。因此,最简单的方

似乎有几种解决方案,它们都分为多个步骤,例如:。 *复制和删除 *使用本机wincommand或pwoershell


但是,难道不只是重命名为win_模块吗?或者选择“复制”以在复制后删除源?

我找到了这个问题的一些答案:

首先要指出的是,这是针对远程windows主机的。对于Unix系统,我们已经在stackoverflow中找到了很多答案,而对于windows则不然

没有win_重命名模块,也没有带有重命名选项的win_文件。无法使用win_copy,因为该文件已在远程系统上。因此,最简单的方法是使用本地windows命令

- name: rename the {{ source_name }} to  {{ target_name }}
  win_command: "cmd.exe /c rename {{ destination_folder }}\\{{ source_name }} {{ target_name }}"

MBushveld,我看到您的windows“rename”命令在这种情况下很好地完成了这个任务。但一般来说,Powershell命令涵盖的环境范围更广,并且针对特定情况具有更多开关/标志选项。例如,查看Powershell的“重命名项”命令。因此,如果下次Windows命令出现问题,您可以编写一个简短的Powershell脚本,并使用所需的任何命令行参数从Ansible调用它。在这篇文章的底部是我编写的一个powershell脚本,用于验证两个文本文件的内容是否完全相同。我使用Ansible中的“script:”命令调用带有如下参数的脚本

- name: verify the file contents match
  script: filesAreSame.ps1  "C:/Temp/" "file1.txt" "file2.txt" 
  register: result
- set_fact: filesMatch="{{result.stdout_lines.4 | bool}}"
Ansible会将脚本移动到远程主机,执行它,然后删除它。如果需要,您可以像我一样在Ansible中使用“register:”命令来捕获脚本返回的任何值。下面是“filesareame.ps1”Powershell脚本的内容

# verifys that the specified files contain the same text
param(
    [string]$uncPath,
    [string]$uncFile1,
    [string]$uncFile2
)
$uncFullFileName1 = $uncPath + $uncFile1
$uncFullFileName2 = $uncPath + $uncFile2
$filetext1=[System.IO.File]::ReadAllText($uncFullFileName1).TrimStart().TrimEnd()
$filetext2=[System.IO.File]::ReadAllText($uncFullFileName2).TrimStart().TrimEnd()
# verify first file is not empty
if ($filetext1 -eq "")
{
    return "ERROR: Source file is empty"
}
# case sensitive comparison
if ($filetext1 -cne $filetext2)
{
    return "ERROR: Files are not the same"
}
return $TRUE

使用remote_src,可以直接在远程系统上工作