首页 > 解决方案 > 如何从 Ansible 管理 var value off Powershell 中的目录

问题描述

Ansible:2.9 PowerShell:5 操作系统:w2k16 服务器

大家好!

我在 Windows 目标主机中使用“只读(仅适用于文件夹中的文件)”创建了一个目录。我需要删除这个属性。

我在 Powershell 中编写了这段代码:

- name: "Change rules dir for all"
  win_shell: |
    $mypath= c:\tmp
    $myacl= Get-ACL "$mypath"
    $myaclentry= "everyone","FullControl","Allow"
    $ruleexecutor= New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
    $myacl.SetAccesRule($ruleexecutor)
    $myACL | Set-Acl $mypath
    Get-ACL "$mypath" | fl

但我有这个结果:

错误:

"stderr": "c:\\tmp : The term 'c:\\tmp' is not recognized as the name of a
 cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.
At line:1 char:73
+ ... ::InputEncoding = New-Object Text.UTF8Encoding $false; $mypath=c:\\tmp
+                                                                    ~~~~~~
    + CategoryInfo          : ObjectNotFound: (c:\\tmp:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Get-Acl : Cannot validate argument on parameter 'Path'. 
The argument is null or empty. Provide an argument that is not 
null or empty, and then try the command again.
At line:2 char:17
+ $myacl= Get-ACL \"$mypath\"
+ 
...

问题:

再次感谢!

标签: powershellansiblepowershell-5.0

解决方案


我有很多回应:

  • 为什么我的代码不运行?有很多原因:

    • 双“\”语法。
    • 因为在我的系统中找不到“SetAccesRule”,所以我需要从 AD 服务器修改 GPO。
    • 当我获得值变量时,win_shell ansible 模块中的显式语法。
    • 路径中 ' 或 " 之间的区别(是的,下次我将创建这个主题的问题)。
  • 为什么“\”无法识别?

  • 如何使用 Powershell 更改 dir 中的简单属性?

    • 我不知道,我忽略了“只读”,因为我可以在目录中写入。更多信息在这里:how-to-remove-read-only-attribute-of-a-folder-by-powershell 但是当我执行此代码时,$folder.Attributes -= 'ReadOnly'我的文件更改为隐藏文件。那是我忽略这个“只读”的另一个原因。

最后,我的解决方案包含在 Powershell 命令中:

task: Create dir
win_shell: |
  New-Item -Path c:\temp -ItemType directory # Of corse here without double '\\'

推荐阅读