Как обработать кнопку, чтобы открыть файл с помощью Powershell? - PullRequest
0 голосов
/ 11 июня 2019

Я хочу открыть файл после выбора файла с помощью графического интерфейса. Когда я пробую свой код, я не могу открыть выбранный файл. Возвращает Get-Content. Не удается найти путь. Любой может помочь мне, пожалуйста.

Function File ($InitialDirectory)
{
    Add-Type -AssemblyName System.Windows.Forms
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.Title = "Please Select File"
    $OpenFileDialog.InitialDirectory = $InitialDirectory
    $OpenFileDialog.filter = “All files (*.*)| *.*”
    If ($OpenFileDialog.ShowDialog() -eq "Cancel") 
    {
    [System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0, 
    [System.Windows.Forms.MessageBoxIcon]::Exclamation)
    }   $Global:SelectedFile = $OpenFileDialog.SafeFileName


    Get-Content "$Global:SelectedFile" | ForEach-Object {
    $_.Trim()
    } | Where-Object {


    $_ -notmatch '^(;|$)'
    } | ForEach-Object {
    if ($_ -match '^\[.*\]$') {
        $section = $_ -replace '\[|\]'
        $ini_file[$section] = @{}
    } else {
        $key, $value = $_ -split '\s*=\s*', 2
        $ini_file[$section][$key] = $value
    }
    }

}


Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.AutoSize                   = $true
$Form.text                       = "OpenFile"
$Form.TopMost                    = $true
#----------------------

$Choose1                      = New-Object system.Windows.Forms.Label
$Choose1.text                 = "MLs"
$Choose1.AutoSize             = $true
$Choose1.width                = 25
$Choose1.height               = 10
$Choose1.location             = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor            = "#000000"

$Sel                        = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize               = $true
$Sel.width                  = 150
$Sel.height                 = 30
$Sel.location               = New-Object System.Drawing.Point(120,40)
$Sel.Text                   = "Selected"

$Choose2                        = New-Object System.Windows.Forms.Button
$Choose2.text                   = "Select File"
$Choose2.AutoSize               = $true
$Choose2.width                  = 90
$Choose2.height                 = 20
$Choose2.location               = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor              = "#ffffff"
$Choose2.BackColor              = "#093c76"

$Close                         = New-Object system.Windows.Forms.Button
$Close.BackColor               = "#6996c8"
$Close.text                    = "Close"
$Close.width                   = 98
$Close.height                  = 30
$Close.location                = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------

$Choose2.Add_Click({Sel_File
$Sel.Text = $Global:SelectedFile
}) 


$Form.Controls.AddRange(@($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()

Мое ожидание, я могу открыть файл, потому что я хочу обработать файл. Файл, который я хочу открыть, - это файл .INI. Пожалуйста, помогите всем. Спасибо

EDITED

Function File ($InitialDirectory)
{
    Add-Type -AssemblyName System.Windows.Forms
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.Title = "Please Select File"
    $OpenFileDialog.InitialDirectory = $InitialDirectory
    $OpenFileDialog.filter = “All files (*.*)| *.*”
    If ($OpenFileDialog.ShowDialog() -eq "Cancel") 
    {
    [System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0, 
    [System.Windows.Forms.MessageBoxIcon]::Exclamation)
    }   $Global:SelectedFile = $OpenFileDialog.FileName
}

Function Get-IniContent ($Global:SelectedFile)
{
    $ini = @{}
    switch -regex -file $Global:SelectedFile
    {
        “^\[(.+)\]” # Section
        {
            $section = $matches[1]
            $ini[$section] = @{}
            $CommentCount = 0
        }
        “^(;.*)$” # Comment
        {
            $value = $matches[1]
            $CommentCount = $CommentCount + 1
            $name = “Comment” + $CommentCount
            $ini[$section][$name] = $value
        } 
        “(.+?)\s*=(.*)” # Key
        {
            $name,$value = $matches[1..2]
            $ini[$section][$name] = $value
        }
    }
    return $ini
}

$iniContent = Get-IniContent $Global:SelectedFile
$Region = $iniContent[“Location”]


Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.AutoSize                   = $true
$Form.text                       = "OpenFile"
$Form.TopMost                    = $true
#----------------------

$Choose1                      = New-Object system.Windows.Forms.Label
$Choose1.text                 = "MLs"
$Choose1.AutoSize             = $true
$Choose1.width                = 25
$Choose1.height               = 10
$Choose1.location             = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor            = "#000000"

$Sel                        = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize               = $true
$Sel.width                  = 150
$Sel.height                 = 30
$Sel.location               = New-Object System.Drawing.Point(120,40)
$Sel.Text                   = "Selected"

$Choose2                        = New-Object System.Windows.Forms.Button
$Choose2.text                   = "Select File"
$Choose2.AutoSize               = $true
$Choose2.width                  = 90
$Choose2.height                 = 20
$Choose2.location               = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor              = "#ffffff"
$Choose2.BackColor              = "#093c76"

$Close                         = New-Object system.Windows.Forms.Button
$Close.BackColor               = "#6996c8"
$Close.text                    = "Close"
$Close.width                   = 98
$Close.height                  = 30
$Close.location                = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------

$Choose2.Add_Click({File
$Sel.Text = $Global:SelectedFile
}) 



$Form.Controls.AddRange(@($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()

Я использую отредактированный код, но не могу обработать кнопку. Я хочу прочитать раздел INI [Местоположение] после выбора файла. С этим кодом раздел уже напечатан, прежде чем я выберу файл.

Ответы [ 2 ]

0 голосов
/ 11 июня 2019

Для этого вам вообще не нужны глобальные переменные. По сути, основная форма должна захватывать $Sel.Text из диалогового окна в переменную, проверить, не является ли это значением по умолчанию «Выбрано», и это должно сделатьэто:

function Select-File ($InitialDirectory) {
    Add-Type -AssemblyName System.Windows.Forms
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.Title = "Please Select File"
    $OpenFileDialog.InitialDirectory = $InitialDirectory
    $OpenFileDialog.filter = "All files (*.*)| *.*"
    If ($OpenFileDialog.ShowDialog() -eq "Cancel") {
        [System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0, 
        [System.Windows.Forms.MessageBoxIcon]::Exclamation)
        $result = $null
    } 
    else { 
        $result = $OpenFileDialog.FileName
    }
    $OpenFileDialog.Dispose()

    return $result
}

function Get-IniContent ($FilePath) {
    $ini = @{}
    switch -regex -file $FilePath
    {
        "^\[(.+)\]" # Section
        {
            $section = $matches[1]
            $ini[$section] = @{}
            $CommentCount = 0
        }
        "^(;.*)$" # Comment
        {
            $value = $matches[1]
            $CommentCount = $CommentCount + 1
            $name = "Comment" + $CommentCount
            $ini[$section][$name] = $value
        } 
        "(.+?)\s*=(.*)" # Key
        {
            $name,$value = $matches[1..2]
            $ini[$section][$name] = $value
        }
    }
    return $ini
}

###############
# Main routine
###############

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.AutoSize                   = $true
$Form.text                       = "OpenFile"
$Form.TopMost                    = $true
#----------------------

$Choose1                      = New-Object system.Windows.Forms.Label
$Choose1.text                 = "MLs"
$Choose1.AutoSize             = $true
$Choose1.width                = 25
$Choose1.height               = 10
$Choose1.location             = New-Object System.Drawing.Point(28,20)
$Choose1.ForeColor            = "#000000"

$Sel                        = New-Object system.Windows.Forms.TextBox
$Sel.AutoSize               = $true
$Sel.width                  = 150
$Sel.height                 = 30
$Sel.location               = New-Object System.Drawing.Point(120,40)
$Sel.Text                   = "Selected"

$Choose2                        = New-Object System.Windows.Forms.Button
$Choose2.text                   = "Select File"
$Choose2.AutoSize               = $true
$Choose2.width                  = 90
$Choose2.height                 = 20
$Choose2.location               = New-Object System.Drawing.Point(28,38)
$Choose2.ForeColor              = "#ffffff"
$Choose2.BackColor              = "#093c76"
$Choose2.Add_Click({ $Sel.Text = Select-File })

$Close                         = New-Object system.Windows.Forms.Button
$Close.BackColor               = "#6996c8"
$Close.text                    = "Close"
$Close.width                   = 98
$Close.height                  = 30
$Close.location                = New-Object System.Drawing.Point(450,190)
$Close.Add_Click({$Form.Close()})
#----------

$Form.Controls.AddRange(@($Choose1, $Sel, $Choose2, $Close))
[void] $Form.ShowDialog()

# if the user did not fill in anything and left the default text of "Selected", set the result to null
$selectedFile = if ($Sel.Text -ne "Selected") { $Sel.Text } else { $null }

# clean up the form
$Form.Dispose()


# here, we test if there is a file selected and if it exists
if ($selectedFile -and (Test-Path -Path $selectedFile -PathType Leaf)) {
    Write-Host "Reading INI file '$($selectedFile)'"
    $iniContent = Get-IniContent $selectedFile
    $Region = $iniContent["Location"]
    $region
}
else {
    Write-Warning "The dialog was cancelled or the selected file cannot be found."
}
0 голосов
/ 11 июня 2019

Согласно моему комментарию, вам нужно изменить $OpenFileDialog.SafeFileName на $OpenFileDialog.FileName.

# SafeFileName = "Config.ini"
# FileName = "\\UNC\Path\Config.ini" or "C:\Temp\Config.ini"

Function File ($InitialDirectory) {
    Add-Type -AssemblyName System.Windows.Forms
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.Title = "Please Select File"
    $OpenFileDialog.InitialDirectory = $InitialDirectory
    $OpenFileDialog.filter = “All files (*.*)| *.*”
    If ($OpenFileDialog.ShowDialog() -eq "Cancel") 
    {
    [System.Windows.Forms.MessageBox]::Show("No File Selected. Please select a file !", "Error", 0, 
    [System.Windows.Forms.MessageBoxIcon]::Exclamation)
    }   $Global:SelectedFile = $OpenFileDialog.FileName


    Get-Content "$Global:SelectedFile" | ForEach-Object {
    $_.Trim()
    } | Where-Object {


    $_ -notmatch '^(;|$)'
    } | ForEach-Object {
        if ($_ -match '^\[.*\]$') {
            $section = $_ -replace '\[|\]'
            $ini_file[$section] = @{}
        } else {
            $key, $value = $_ -split '\s*=\s*', 2
            $ini_file[$section][$key] = $value
        }
    }

}

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...