我正在使用 powershell 和 wpf 构建一个 GUI。我想在工具运行时更改按钮的内容。但当其他命令完成后它就发生了变化。我尝试将命令作为作业启动,因为我读到 powershell 是同步工作的。即使更改内容的命令位于第一个位置
遵循我的代码:
try {
$btnCreateUser1.Content = "Bitte warten..."
$oldinformationJob = Invoke-Command -AsJob -ComputerName test -Credential $cred -ScriptBlock {Get-Aduser -identity $using:ReferenceUserTextBox.Text -Properties * -Credential $Using:cred}
$oldinformation = Wait-Job $oldinformationJob | Receive-Job
$Passwort = 'test'
$Attributes = @{
SAMAccountname = $NewUserUsernameTextBox.Text
UserPrincipalName = "$($NewUserUsernameTextBox.Text)@test.de"
Name = "$($FirstNameTextBox.Text) $($LastNameTextBox.Text)"
AccountPassword = (ConvertTo-SecureString $Passwort -AsPlainText -Force)
Path = ($oldinformation.DistinguishedName).Split(",",2)[1]
GivenName = $FirstNameTextBox.Text
Surname = $LastNameTextBox.text
Enabled =$true
DisplayName = "$($LastNameTextBox.Text), $($FirstNameTextBox.Text)"
City = ""
PostalCode = ""
Country = ""
State = ""
Company = $oldinformation.company
StreetAddress = $oldinformation.StreetAddress
OfficePhone = $NummerTextBox.text
Department = $oldinformation.Department
Office = $RaumTextBox.Text
Title = $PositionBox.Text
HomeDirectory = "\\test\user\Home\$($NewUserUsernameTextBox.Text)"
Homedrive = "U"
}
Invoke-Command -AsJob -ComputerName test -Credential $cred -ScriptBlock {
New-ADUser @Using:Attributes -Credential $Using:cred
}
Start-Sleep -Seconds 5
Invoke-Command -AsJob -ComputerName test -Credential $cred -ScriptBlock {Get-ADPrincipalGroupMembership -Identity $($Using:oldinformation.SAMAccountname) -ResourceContextServer "test" -Credential $Using:cred | ForEach-Object {Add-ADGroupmember -Identity $_.SAMAccountname -Members $($Using:Attributes.SAMAccountname) -Credential $Using:cred -ErrorAction SilentlyContinue}}
[System.Windows.Forms.MessageBox]::Show("Der User $($NewUserUsernameTextBox.Text) wurde erstellt ","Active Directory Tool",0)
$btnCreateUser1.Content = "Benutzer erstellen"
请参阅:在 Powershell 中使用调度程序调用和运行空间
WPF 控件(如脚本中的按钮)只能从 UI 线程进行更新。如果您尝试从不同的线程(例如作业线程)更新控件,则需要使用
Dispatcher.Invoke
方法来编组对 UI 线程的调用。
$btnCreateUser1.Dispatcher.Invoke({
$btnCreateUser1.Content = "Bitte warten..."
}, [System.Windows.Threading.DispatcherPriority]::Background)