我一直在与Powershell合作一段时间,它不是理想的编程环境,但却被我的程序困住了。
我的程序是一个带有选取框进度条和搜索作业的GUI。
我的程序执行的操作:使用Powershell运行脚本后,如果模式为MTA,它将在STA模式下重新启动Powershell。之后,它会询问文件夹位置。输入文件夹位置后,它将启动搜索作业,并在该位置搜索文件。每个文件都将存储到一个数组中。该数组将打印到tempfile.txt中,该文件将保存在桌面上。同时,作业正在搜索GUI将显示带有Marquee Progress栏的表单的文件。
我的程序需要做什么:在完成搜索和存储文件的工作后,它必须关闭表单。
我已尝试使用$ formSearchingFiles.Close()命令,但我注意到Jobs无法关闭其“父”线程,因此该作业将无法关闭表单。
我还尝试使用Wait-Job cmdlet解决它,但是Marquee Progress栏会冻结,或者表单根本不会显示。
我在互联网上寻找解决方案但我找不到适合这个问题的解决方案。我正在考虑多处理,但我不知道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
}
}
答案 0 :(得分: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