【问题标题】:powershell cannot bind parameter 'NewPassword'powershell 无法绑定参数'NewPassword'
【发布时间】:2017-09-21 09:08:35
【问题描述】:

我正在尝试编写一个程序,使用 Python 中的 PowerShell 命令更改用户的 Windows 密码。

我试过了。

import subprocess

password = input('Enter New Password: ')

c1 = "C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe"
c2 = "Set-ADAccountPassword john -NewPassword " + password + " –Reset".format(password)

c = subprocess.call([c1, c2])

print (c)

但它给出了一个错误

Set-ADAccountPassword : Cannot bind parameter 'NewPassword'.  Cannot convert the "mynewpass1" value of type "System.String" to type "System.Security.SecureString".

我在https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/convertto-securestring?view=powershell-5.1 上读到,您已使用诸如此类的命令将纯字符串转换为安全字符串。

PS C:\> $Secure_String_Pwd = ConvertTo-SecureString "P@ssW0rD!" -AsPlainText -Force

我尝试重写我的程序,但我得到一个无效的语法错误。甚至有可能做到这一点吗? 这是我现在正在使用的内容。

import subprocess

password = input('Enter New Password: ')


a1, a2 = "C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", "$PwdVar = ConvertTo-SecureString "{0}" -AsPlainText -Force; Set-ADAccountPassword jm09580 -NewPassword $PwdVar –Reset"
c = subprocess.call([a1, a2.format(password)])

print (c)

【问题讨论】:

  • "$PwdVar = ConvertTo-SecureString "{0}" -AsPlain..." -> "$PwdVar = ConvertTo-SecureString '{0}' -AsPlain..."
  • 如果你在双引号字符串中使用非转义双引号,你会得到 2 个单独的字符串,它们之间有一个(很可能是无效的)表达式。
  • 运行了,但它似乎将我锁定在我的帐户之外,并且新密码不起作用。
  • 您在实际运行之前检查(即显示)您正在运行的命令吗?

标签: python powershell powershell-3.0


【解决方案1】:

您遇到的问题是您的引号没有被正确转义。您需要在正确的位置为命令行参数加上引号,然后为变量加上引号。它变得非常混乱。

PowerShell 有一个功能可以帮助解决这个问题,您可以将脚本作为 Base64 编码字符串传递给它。它不会包含要转义的特殊字符。

我几乎没有 Python 技能,也没有测试过这个例子,它只是为了帮助你走上正轨:

import base64
a1, a2 = "C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", "$PwdVar = ConvertTo-SecureString "{0}" -AsPlainText -Force; Set-ADAccountPassword jm09580 -NewPassword $PwdVar –Reset"
data = base64.b64encode(a2.format(password))
c = subprocess.call([a1, '-EncodedCommand ' + data])

你的命令基本上应该是这样的:

PowerShell -EncodedCommand MQAuAC4AMQAwACAAfAAgACUAIAB7ACAAIgBQAG8AdwBlAHIAUwBoAGUAbABsACAAUgBvAGMAawBzACIAIAB9AA==

Powershell 将解码字符串并运行里面的命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多