我一直试图让pywinrm模块远程运行New-Mailbox
Powershell cmdlet。这就是我到目前为止所做的:
import winrm
ps_text = "$pass = ConvertTo-SecureString -String '%s' -AsPlainText -Force; \
Add-PSSnapIn Microsoft.Exchange.Management.Powershell.E2010; \
New-Mailbox -UserPrincipalName '%s@contoso.lan' \
-Alias '%s' -Name '%s' -Password $pass \
-Firstname '%s' \
-Lastname '%s' \
-DisplayName '%s' \
-PrimarySmtpAddress '%s'" % \
('password123',
'jfd',
'john.doe',
'John Doe',
'John',
'Doe',
'John Doe',
'john.doe@contoso.co.uk')
remote = winrm.Session('https://contoso.co.uk:5986', auth=('ps_remote', 'irrelevant'))
r = remote_session.run_cmd("powershell", ["-version", "2.0", "-c", ps_text])
这是我得到的输出:
New-Mailbox:值不能为null。参数名称:serverSettings At line:1 char:147 + $ pass = ConvertTo-SecureString -String' password123' -AsPlainText -Force; Add-PSSnapIn Microsoft.Exchange.Management.Powershell.E2010; New-Mailbox<<<< -UserPrincipalName' jfd@contoso.lan' -Alias ' john.doe' -Name' John Doe' -Password $ pass -Firstname' John' -Lastname' Doe' -DisplayName' John Doe' -PrimarySmtpAddress' john.doe@contoso.co.uk' + CategoryInfo:NotSpecified:(:) [New-Mailbox],ArgumentNullException + FullyQualifiedErrorId:System.ArgumentNullException,Microsoft.Exchange.Management.RecipientTasks.NewMailbox
我觉得它并不像$ pass那样没有引用,所以我用单引号将它包起来得到:
New-Mailbox:无法绑定参数'密码'。无法转换 " $传递" type" System.String"的值输入 " System.Security.SecureString"。行:1个字符:231 + $ pass = ConvertTo-SecureString -String' password123' -AsPlainText -Force; Add-PSSnapIn Microsoft.Exchange.Management.Powershell.E2010; New-Mailbox -UserPrincipalName' jfd@contoso.lan' -Alias' john.doe' -Name' John Doe' -Password<<<< ' $ pass' -Firstname' John' -Lastname' Doe' -DisplayName' John Doe' -PrimarySmtpAddress ' john.doe@contoso.co.uk' + CategoryInfo:InvalidArgument:(:) [New-Mailbox],ParameterBindingException + FullyQualifiedErrorId:CannotConvertArgumentNoMessage,Microsoft.Exchange.Management.RecipientTasks.NewMailbox
强调我的。现在它从字面上解释它而不是扩展$ pass变量。有什么方法可以让我正确执行这个吗?
一些注意事项:
run_ps
记录的winrm.Session
方法,因为它没有针对远程端的正确版本的Powershell运行(此处需要版本2.0,因为'什么是Exchange管理管理单元所需的内容。$pass;
,标准输出实际上会返回System.Security.SecureString
,这使得在第一个示例中它会抱怨空参数更奇怪。New-PSSession
来导入远程会话,但实际上无法访问我需要的cmdlet。我还尝试使用Invoke-Command
远程运行脚本块,但即使可以成功导入Snap-in,它也不会运行实际的cmdlet。New-Mailbox
的示例相当稀疏,或者在这种情况下我的Google-fu可能很弱。答案 0 :(得分:0)
在PowerShell中,单引号将阻止变量扩展。
我的建议是:
$pass
-serverSettings
,而不是-Password
-serverSettings
的值(我在Exchange文档中找不到此参数,但检查您的版本是否存在)pywinrm
希望这有帮助!干杯