0

我一直在使用 Powershell 一段时间,它不是理想的编程环境,但被我的程序卡住了。

我的程序是一个带有选取框进度条和搜索作业的 GUI。

我的程序的作用:在使用 Powershell 运行脚本后,如果模式为 MTA,它将以 STA 模式重新启动 Powershell。之后它会询问文件夹位置。输入文件夹位置后,它将开始搜索作业并在该位置搜索文件。每个文件都将存储到一个数组中。该数组将打印到 tempfile.txt 中,该文件将保存在您的桌面上。同时,工作是搜索文件,GUI 将显示一个带有选取框进度条的表单。

我的程序需要做什么:在搜索和存储文件完成工作后,它必须关闭表单。

我试过用 $formSearchingFiles.Close() 命令来做,但我注意到乔布斯无法关闭他们的“父”线程,所以这个工作将无法关闭表单。

我也尝试使用 Wait-Job cmdlet 来解决它,但随后选取框进度条将冻结,或者根本不会显示表单。

我在互联网上寻找了很多解决方案,但我找不到适合这个问题的解决方案。我在考虑多处理,但我不知道这在 Powershell 2.0 中是否可行(我仅限于 2.0 或更低版本)。

也不知道有没有办法让Search-Job通知主线程任务完成,这样主线程就可以继续执行程序,而不会冻结进度条。

我希望我已经对程序和我的问题进行了足够的解释。

# Get the path of the script
$scriptPath = ((Split-Path $script:MyInvocation.MyCommand.Path) + "\")
$scriptName = $MyInvocation.MyCommand.Name
$script = $scriptPath + $scriptName

# Check if powershell is running in STA(Single Threaded Apartment) or MTA(Multi Threaded Apartment) mode.
# If it is running in MTA mode then restart Powershell in STA mode.
if ([threading.thread]::CurrentThread.GetApartmentState() -eq "MTA") 
{
    Write-Host Restarting Powershell in STA mode
    & $env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe -sta "& {&'$script'}"
}
else
{
    $folderPath = $currentFolderLocation.Text
    $tempFile = $currentStagingLocation.Text
    $tempFile += "\fileArray.txt"

    function OnApplicationLoad {    
        return $true #return true for success or false for failure
    }

    function OnApplicationExit {
        $script:ExitCode = 0 #Set the exit code for the Packager
    }

    function Call-Searching_pff {
        [void][reflection.assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        [void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        [void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
        [void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        [void][reflection.assembly]::Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        [void][reflection.assembly]::Load("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        [void][reflection.assembly]::Load("System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
        [void][reflection.assembly]::Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        [void][reflection.assembly]::Load("System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

        [System.Windows.Forms.Application]::EnableVisualStyles()
        $formSearchingFiles = New-Object 'System.Windows.Forms.Form'
        $label = New-Object 'System.Windows.Forms.Label'
        $progressbar = New-Object 'System.Windows.Forms.ProgressBar'
        $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'

        $FormEvent_Load={

        $folderPath = &read-host "Enter path"
        $tempFile = (([Environment]::GetFolderPath("Desktop")) + "\tempfile.txt" )

            $SearchJob = Start-Job -scriptblock {
                param ($folderPath, $tempFile)
                $fileArray = @()
                # Get all files and folders under the specified path
                $items = Get-ChildItem -Path $folderPath -Recurse
                foreach ($item in $items)
                {
                    # Check if the item is a file or a folder
                    if (!($item.PSIsContainer)) 
                    {
                        # Extract path of file with path of entered folder
                        $extractedPath = $item.FullName
                        $extractedPath = $extractedPath.Replace($folderPath, "")
                        $fileArray += $extractedPath
                    }
                }
                # Save array in temporary file
                $fileArray | out-file $tempFile
                $formSearchingFiles.Close() #Does not work inside job :(

            } -ArgumentList @($folderPath, $tempFile)       
        }

        $Form_StateCorrection_Load=
        {
            #Correct the initial state of the form to prevent the .Net maximized form issue
            $formSearchingFiles.WindowState = $InitialFormWindowState
        }

        $Form_Cleanup_FormClosed=
        {
            #Remove all event handlers from the controls
            try
            {
                $formSearchingFiles.remove_Load($FormEvent_Load)
                $formSearchingFiles.remove_Load($Form_StateCorrection_Load)
                $formSearchingFiles.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]{ }
        }

        # formSearchingFiles
        $formSearchingFiles.Controls.Add($label)
        $formSearchingFiles.Controls.Add($progressbar)
        $formSearchingFiles.ClientSize = '394, 122'
        $formSearchingFiles.FormBorderStyle = 'FixedDialog'
        $formSearchingFiles.MaximizeBox = $False
        $formSearchingFiles.Name = "formSearchingFiles"
        $formSearchingFiles.StartPosition = 'CenterScreen'
        $formSearchingFiles.Text = "Compatibility Checker"
        $formSearchingFiles.add_Load($FormEvent_Load)

        # label
        $label.Location = '12, 27'
        $label.Name = "label"
        $label.Size = '368, 26'
        $label.TabIndex = 1
        $label.Text = "Searching for files, please wait.."
        $label.TextAlign = 'MiddleCenter'

        # progressbar
        $progressbar.Location = '12, 68'
        $progressbar.MarqueeAnimationSpeed = 40
        $progressbar.Name = "progressbar"
        $progressbar.Size = '370, 30'
        $progressbar.Style = 'Marquee'
        $progressbar.TabIndex = 0

        #Save the initial state of the form
        $InitialFormWindowState = $formSearchingFiles.WindowState
        #Init the OnLoad event to correct the initial state of the form
        $formSearchingFiles.add_Load($Form_StateCorrection_Load)
        #Clean up the control events
        $formSearchingFiles.add_FormClosed($Form_Cleanup_FormClosed)
        #Show the Form
        return $formSearchingFiles.ShowDialog()
    } #End Function

    #Call OnApplicationLoad to initialize
    if((OnApplicationLoad) -eq $true)
    {
        #Call the form
        Call-Searching_pff | Out-Null
        #Perform cleanup
        OnApplicationExit
    }
}
4

1 回答 1

2

我找到了解决我自己问题的方法。解决方案:同步哈希表作为线程间的“通信纽带”

创建哈希表后,您可以向其中添加变量和对象。所有线程(您授予对哈希的访问权限)都可以读取/写入这些变量和对象。

创建同步。哈希表:

$syncHash = [hashtable]::Synchronized(@{})
#Where $syncHash is the name of your hash table

将变量和对象添加到哈希表:

$syncHash.ProgressBar = $progressBar
#Create new variable ProgressBar in hash table and assign $progressBar to it

创建新线程并允许使用哈希表:

$processRunspace =[runspacefactory]::CreateRunspace()
$processRunspace.ApartmentState = "STA"
$processRunspace.ThreadOptions = "ReuseThread"          
$processRunspace.Open()
$processRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)   

$psCmd = [PowerShell]::Create().AddScript({
     #Your Thread Code Here
})
$psCmd.Runspace = $processRunspace
$data = $psCmd.BeginInvoke() 

从新线程更改 $progressBar 的值:

$syncHash.ProgressBar.Value = 1

感谢: http: //learn-powershell.net/2012/10/14/powershell-and-wpf-writing-data-to-a-ui-from-a-different-runspace/

于 2013-05-03T21:26:22.857 回答