首页 > 解决方案 > 调用脚本时PowerShell冻结

问题描述

我编写了一个 GUI 来集中一些小的 PowerCLI 脚本。在其中一个小脚本中,我使用“Get-VAMIService”语句检查 vCenter 运行状况。如果我只是运行这个脚本,一切正常,但如果我从我的 GUI 调用脚本,GUI 和被调用的脚本,冻结。我发现,在这个“Get-VAMIService”语句中,一切都冻结了。

$service1 = Get-VAMIService -Name applmgmt

我已经用 DoEvents() 试过了。

[System.Windows.Forms.Application]::DoEvents() 

如果我在 ISE 或普通的 PowerShell 中运行它并不重要。

有谁知道,为什么脚本在从 GUI 脚本调用时冻结,但在自行执行时运行良好?

编辑:我忘了提,我使用的是 William Lam 的 VAMI-Summary。 https://www.virtuallyghetto.com/2017/01/exploring-new-vcsa-vami-api-wpowercli-part-1.html

一个带有一个按钮的 GUI,可以调用脚本进行重新创建:

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$window = New-Object System.Windows.Forms.Form
$window.Width = 540
$window.Height = 400
$window.FormBorderStyle = 'Fixed3D'
$window.MaximizeBox = $false


$windowButton = New-Object System.Windows.Forms.Button
$windowButton.Location = New-Object System.Drawing.Point(30,40)
$windowButton.Size = New-Object System.Drawing.Size (75,75)
$windowButton.BackColor = "white"
$windowButton.ForeColor = "Black"


$Textfieldbut1 = New-Object System.Windows.Forms.Label
$Textfieldbut1.text = "Test"
$Textfieldbut1.Location = New-Object System.Drawing.Point(22, 120)
$Textfieldbut1.Size = New-Object System.Drawing.Size (300,50)
$Textfieldbut1.BackColor = [System.Drawing.Color]::FromName("Transparent")


$window.Controls.Add($windowButton)
$window.Controls.Add($Textfieldbut1)

$windowButton.Add_Click({
    ."$PSScriptRoot\Script.ps1"

})

[void]$window.ShowDialog()

这是它冻结的被调用脚本。它在“$services = $vMonAPI.list_details()”处冻结。

Set-PowerCLIConfiguration -InvalidCertificateAction ignore -confirm:$false | 

Out-Null

Import-Module VMware.VimAutomation.Cis.Core

$vcenter = "vCenter Name"
$path1 = "C:\PS2\securestring1.txt"
$path2 = "C:\PS2\"
$localadmin1 = 'administrator@vspheresh.local'
$password1 = cat $path1 | convertto-securestring -Key (1..16) 
$global:credlocal = new-object -typename System.Management.Automation.PSCredential -argumentlist $localadmin1, $password1
Connect-CisServer -server $vcenter -credential $credlocal
Write-Host "Connected..." -ForegroundColor "green"
$vMonAPI = Get-CisService 'com.vmware.appliance.vmon.service'
$services = $vMonAPI.list_details()
$services

Disconnect-CisServer -Force:$true -confirm:$false | Out-Null

编辑 2:如果我从没有 GUI 的脚本调用脚本,它完全可以正常工作。只有当我在 GUI 脚本中单击按钮时,它才会冻结并崩溃。

标签: powershelluser-interfacepowercli

解决方案


推荐阅读