如何使用python和powershell向Windows 10添加用户

问题描述 投票:0回答:1

[我正在尝试使用使用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-3.x windows powershell subprocess
1个回答
0
投票

发现我只有一堆语法错误。我现在真的很傻。这是有关如何通过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 + "}"])
© www.soinside.com 2019 - 2024. All rights reserved.