为了让新员工更容易通过PowerShell连接到Exchange,我使用powershell编写一个快速的小工具:winforms。
该工具只包含几个按钮,文本字段和信息性文本,因此用户可以从一个UI管理Exchange envoirement。
position: relative
如您所见,第一个“设置凭据”按钮允许用户通过默认的获取凭据输入凭据。
第二个按钮'Connect to Exchange'使用$ UserCredentials启动新的PSSession登录。
我面临的问题是,当按下连接按钮时,我会收到一条错误,指出-credential值为Null。
查询$ UserCredential也会给出一个空行。
似乎输入凭据后,他们不会被存储,因为它们是通过按钮功能调用的。
我试着查一下,但大多数的白痴都很模糊。
富尔代码:
h1
答案 0 :(得分:1)
您需要将$UserCredential
设为全局。
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$Exchange_Manager = New-Object Windows.Forms.Form
$Exchange_Manager.TopMost = $true
# create a global empty credential object
$Global:UserCredential = [System.Management.Automation.PSCredential]::Empty
#Session Initation 1
#1 Set Credentials Button
$Set_Credential = New-Object System.Windows.Forms.Button
$Set_Credential.Top = "5"
$Set_Credential.Left = "5"
$Set_Credential.Anchor = "Left,Top"
$Set_Credential.Text = 'Set Credentials'
$Set_Credential.add_Click({
$Global:UserCredential = Get-Credential
})
$Exchange_Manager.Controls.Add($Set_Credential)
#2 Current Credentials
#3 Connect to Exchange Online
$Exchange_Connect = New-Object System.Windows.Forms.Button
$Exchange_Connect.Top = "5"
$Exchange_Connect.Left = "150"
$Exchange_Connect.Anchor ="Left,Top"
$Exchange_Connect.Text = 'Connect'
$Exchange_Connect.add_Click({
if ($Global:UserCredential -ne [System.Management.Automation.PSCredential]::Empty) {
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential "$Global:UserCredential" -Authentication Basic -AllowRedirection
Import-PSSession $Session
}
})
$Exchange_Manager.Controls.Add($Exchange_Connect)
#4 Show the dialog and dispose of it afterwards
$Exchange_Manager.ShowDialog()
$Exchange_Manager.Dispose()