首页 > 解决方案 > 无论如何以与 VBA 脚本不同的用户身份运行 powershell

问题描述

我有一个带有按钮的 excel 文件,这些按钮启动 powershell 来执行脚本(将成员添加到组,连接到交换服务器以设置电子邮件帐户等),有 3 个文件有超过 50 个按钮,我们需要每隔几个执行一次天

该脚本实际上是调用powershell并根据excel文件中单元格的值执行添加成员到组等命令。它工作正常,以下是现有代码的示例:

Dim pid As Variant
Dim a As String
Dim i As Long

For i = 1 To ThisWorkbook.Worksheets("Add AD Group & DL").Range("a9999").End(xlUp).Row - 8
a = "powershell -noprofile -command ""&{Add-ADGroupMember -Identity dgroup -members uname}"""
a = Replace(a, "uname", Range("a" & i + 8).Value)
a = Replace(a, "dgroup", Range("g" & i + 8).Value)


exe1 = a

pid = Shell(exe1, vbHide)
Debug.Print exe1

Next i

以下是另一个需要连接到 Exchange 服务器的示例:

Dim pid As Variant
Dim a As String
Dim i As Long

For i = 1 To ThisWorkbook.Worksheets("Create Email Account").Range("b9999").End(xlUp).Row - 8

a = "powershell -noprofile -command ""&{Set-ExecutionPolicy -Scope CurrentUser unrestricted;$serverURI = 'http://hkg-mrs.abcdm001.corp.domain.com/PowerShell/';$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $serverURI -Authentication Kerberos;Import-PSSession $Session}""" _
& ";Get-Mailbox -identity username | Set-Mailbox -RetentionPolicy 'CPA MailBox Folder Policy for General Users'" _
& ";Enable-Mailbox username -Archive" _
& ";Set-Mailbox -Identity username -ArchiveQuota 5GB -ArchiveWarningQuota 4.5GB -emailaddresspolicyenabled $false" _
& ";Set-CASMailbox username -PopEnabled:$False -ImapEnabled:$False" _
& ";Set-Mailbox -Identity username -UserPrincipalName eaddress" _
& ";Remove-PSSession -Session (Get-PSSession)"""

a = Replace(a, "username", Range("b" & i + 8).Value)
a = Replace(a, "eaddress", Range("f" & i + 8).Value)
a = Replace(a, "fname", Range("c" & i + 8).Value)
a = Replace(a, "lname", Range("e" & i + 8).Value)



exe1 = a

        pid = Shell(exe1, vbHide)
        Debug.Print exe1
        Range("h" & i + 8).Interior.Color = XlRgbColor.rgbGreen
        Application.Wait Now + TimeSerial(0, 0, 3)


Next i

但是,当我们使用自己的帐户登录 PC 时,我们现在需要使用不同的帐户(域管理员)来执行脚本。我想实现的方法是要求用户在 excel 中的特定单元格(假设 Sheet1 上的 B1 和 B2)中输入用户名和密码,我想修改 VBA 脚本以引用用户名和密码该特定单元格并运行脚本。

我知道我可以提示凭据窗口获取域管理员凭据,但是由于脚本几乎同时启动 20 个 powershell,因此用户输入密码 20 次并不容易。有什么简单的方法可以实现吗?

太感谢了。

标签: excelvbapowershell

解决方案


推荐阅读