【问题标题】:How to handle button to open a file using Powershell?如何处理按钮以使用 Powershell 打开文件?
【发布时间】:2021-04-22 23:09:48
【问题描述】:

我想在使用 GUI 选择文件后打开文件。当我尝试我的代码时,我无法打开我选择的文件。它返回 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 文件。


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 部分 [位置]。使用此代码,在我选择文件之前已经打印了该部分。

【问题讨论】:

  • $OpenFileDialog.SafeFileName 更改为$OpenFileDialog.FileName。您的 $Global:SelectedFile 显示为文件 BaseName 而不是 FullName。

标签: powershell user-interface


【解决方案1】:

你根本不需要全局变量。基本上,主窗体应该将对话框中的$Sel.Text 捕获到一个变量中,检查这是否不是“Selected”的默认值,应该这样做它:

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."
}

【讨论】:

    【解决方案2】:

    根据我的评论,您需要将$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()
    

    【讨论】:

    • 我更改了它,但我无法读取我选择的文件。它不返回任何东西
    • 那么它将在您的ForeachWhere-Object 呼叫中的某个位置。您能否提供几行您正在寻找的用于测试的 ini 文件?
    • 我无法使用 Foreach 和 Where-Object。我只是用这个$File_ML = Get-Content $Global:SelectedFile 来读取文件。但这不是我需要的。因为我需要阅读 INI 文件的每一部分。任何想法? @德鲁
    猜你喜欢
    • 2014-02-13
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多