[我正在尝试使用使用Powershell添加用户的python脚本将用户添加到Windows 10。
这是我到目前为止的内容:
main.py
import subprocess as sub
import os
username = testUser
passwds = passwordTest
command = """
$nusnm = """ + '"{}"'.format(username) + """
$nuspss = ConvertTo-SecureString """ + '"{}"'.format(passwds) + """ -AsPlainText -Force
New-LocalUser -Name $nusnm -Password $nuspss
Add-LocalGroupMember -Group "Administrators" -Member $nusnm
Get-LocalUser
"""
print(command)
exec = sub.Popen(["powershell","& {" + command + "}"])
如果也有帮助,这是我基于它的Powershell代码,它可以起作用:
$nusnm = Read-Host -Prompt 'What would you like the name of the user to be? '
$nuspss = Read-Host -Prompt -AsSecureString 'Please input a new password for the user '
New-LocalUser $nusnm -Password $nuspss -Confirm
Add-LocalGroupMember -Group "Administrators" -Member $nusnm
Get-LocalUser
当执行此python代码时,我没有得到任何错误,但是也没有得到名为testUser的添加用户。我究竟做错了什么?
非常感谢您的帮助
发现我只有一堆语法错误。我现在真的很傻。这是有关如何通过python向Windows 10添加用户的正确代码。
main.py
import subprocess as sub
import os
username = testUser
passwds = passwordTest
command = """
$nusnm = """ + '"{}"'.format(username) + """
$nuspss = ConvertTo-SecureString """ + '"{}"'.format(passwds) + """ -AsPlainText -Force
New-LocalUser -Name $nusnm -Password $nuspss
Add-LocalGroupMember -Group "Administrators" -Member $nusnm
Get-LocalUser
"""
print(command)
exec = sub.Popen(["powershell","& {" + command + "}"])