选择文件夹并在文本框中写入输出powershell

时间:2016-04-24 18:20:03

标签: user-interface powershell directory

我在powershell中创建了一个应用程序,现在我需要将GUI添加到应用程序中。

在此应用程序中,我需要让用户有机会选择编写文本夹中文件夹的路径。我已经编写了这段代码但是我还没有实现在我创建的texbox中调用get-FolderLocation函数的输出。

enter image description here

有关如何实现这一目标的任何想法?

[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
}

1 个答案:

答案 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})