如何使用Python表示Powershell“ToBase64String”功能
因为我想调用Windows Shell运行命令并从Python获取输出,所以我尝试在Python中编码命令字符串,然后
> powershell -EncodedCommand <base64 string from Python encode>
通过错误而通过使用它来运行它。
Python中的代码看起来像是
s = '''Get-ADUser -Filter ('Surname -eq "aa" -and GivenName -eq "bb" -and Department -eq "cc"') | Select-Object -Property UserPrincipalName'''
bs = bytearray(s, 'utf-16')
base64.b64encode(bs)
,但是,当我使用PowerShell函数将我的命令字符串加密到Base64字符串
PS > $bytes = [System.Text.Encoding]::Unicode.GetBytes("Get-ADUser -Filter ('Surname -eq `"aa`" -and GivenName -eq `"bb`" -and Department -eq `"cc`"') | Select-Object -Property UserPrincipalName")
PS > [Convert]::ToBase64String($bytes)
之后时,我可以获得有效的base64字符串以成功地在普通的Windows Shell上执行此命令。
> powershell -EncodedCommand <base64 string encoded by Powershell in last two steps>
我的问题是这里有什么问题? 还是我还有其他选择来解决问题?例如,使用“ -command”的PowerShell参数直接运行? 实际上,我尝试
> powershell -Command "Get-ADUser -Filter ('Surname -eq `"aa`" -and GivenName -eq `"bb`" -and Department -eq `"cc`"') | Select-Object -Property UserPrincipalName"
了
Get-ADUser : Error parsing query: 'Surname -eq `aa` -and GivenName -eq `bb` -and Department -eq `cc`' Error Message: 's
yntax error' at position: '13'.
At line:1 char:1
+ Get-ADUser -Filter ('Surname -eq `aa` -and GivenName -eq `bb` -and De ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr
osoft.ActiveDirectory.Management.Commands.GetADUser
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,
bs = bytearray(s,'utf-16')
添加:要获得与PowerShell相同的结果,请使用
:
与PowerShell相同:
Note that
bs = bytearray(s, 'utf-16')
adds Byte order mark:To get the same result as PowerShell, use
Then:
which is the same as PowerShell: