我在powershell中创建了一个应用程序,现在我需要将GUI添加到应用程序中。
在此应用程序中,我需要让用户有机会选择或编写文本夹中文件夹的路径。我已经编写了这段代码但是我还没有实现在我创建的texbox中调用get-FolderLocation
函数的输出。
有关如何实现这一目标的任何想法?
[void][System.Reflection.Assembly]::LoadWithPartialName( “System.Windows.Forms”)
[void][System.Reflection.Assembly]::LoadWithPartialName( “Microsoft.VisualBasic”)
#####Define the form size & placement
$form = New-Object “System.Windows.Forms.Form”;
$form.Width = 500;
$form.Height = 150;
$form.Text = $title;
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;
##############Define text label1
$textLabel1 = New-Object “System.Windows.Forms.Label”;
$textLabel1.Left = 25;
$textLabel1.Top = 15;
$textLabel1.Text = "select the folder";
############Define text box1 for input
$textBox1 = New-Object “System.Windows.Forms.TextBox”;
$textBox1.Left = 150;
$textBox1.Top = 10;
$textBox1.width = 200;
$textBox1.Text = "selected folder"
#############define select button
$button = New-Object “System.Windows.Forms.Button”;
$button.Left = 360;
$button.Top = 85;
$button.Width = 100;
$button.Text = “Browse”;
############# the output of calling the get-Folder Location function must be shown in the textbox1
$button.Add_Click({get-Folderlocation}) ;
#############Add controls to all the above objects defined
$form.Controls.Add($button);
$form.Controls.Add($textLabel1);
$form.Controls.Add($textBox1);
$form.ShowDialog();
$textBox1.Text
$selectedDirectory
function get-Folderlocation([string]$Message, [string]$InitialDirectory, [switch]$NoNewFolderButton)
{
$browseForFolderOptions = 0
if ($NoNewFolderButton) { $browseForFolderOptions += 512 }
$app = New-Object -ComObject Shell.Application
$folder = $app.BrowseForFolder(0, $Message, $browseForFolderOptions, $InitialDirectory)
if ($folder) { $selectedDirectory = $folder.Self.Path } else { $selectedDirectory = '' }
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($app) > $null
return $selectedDirectory
}
答案 0 :(得分:1)
您只需将get-FolderLocation
的输出分配到$textBox1.Text
。
由于$textBox1
变量与add_Click()
scriptblock不在同一范围内,因此PowerShell 3.0和4.0将有解决问题的问题。使用Get-Variable -Scope 1
解决此问题:
$button.Add_Click({(Get-Variable -Name textBox1 -Scope 1).Value.Text = Get-Folderlocation})