Powershell SaveFileDialog-弹出两次

时间:2019-07-12 15:58:05

标签: .net winforms powershell savefiledialog

请告诉我为什么在此代码中,SaveFileDialog()两次提示输入文件名。

Function output-scrub{
  [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

  $global:SaveFileDialogNB = New-Object System.Windows.Forms.SaveFileDialog
  $global:SaveFileDialogNB.initialDirectory = "\\server\folder"
  $global:SaveFileDialogNB.filter = "All files (*.*)| *.*"
  $global:SaveFileDialogNB.SupportMultiDottedExtensions = $true
  #$global:SaveFileDialogNB.ShowDialog() | Out-Null
  #just to display the filename value
  $global:SaveFileDialogNB.filename
  #get just filename and the extension into a variable
  #$F1Filename = Split-Path $global:OpenFileDialog.filename -Leaf  ---commented out, only here if we only want to show filename extension alone.
    $global:SaveFileDialogNB.ShowDialog() | Out-Null
    if($SaveFileDialogNB.ShowDialog() -eq 'OK'){
        convertToHashTWO
    }
  return
}


function outPutScrubbedBalances{
    output-scrub
    write-host "file has been saved"
    return
}

这让我发疯了。

1 个答案:

答案 0 :(得分:0)

您曾两次致电$ShowDialog()。在if语句之前一次,在if语句的条件部分中第二次与“ OK”进行比较。

调用一次,捕获对话框结果,然后检查结果:

$result = $yourDialog.ShowDialog()  
if($result  -eq "OK")               
{              
    # Do something
}

或者,只需在if语句的条件部分中调用它并检查结果:

if($yourDialog.ShowDialog() -eq "OK")
{
    # do something
}

旁注:丢弃一次性组件很重要,请不要忽略它。显示对话框并确保使用后将其丢弃的更好方法是:

$dialog = New-Object System.Windows.Forms.SaveFileDialog
try
{
    #Set up dialog, for example
    $dialog.filter = "All files (*.*)| *.*"
    if($dialog.ShowDialog() -eq "OK")
    {
        # do something here, for example
        Write-Host "Save Clicked."
    }
}
finally
{
    if($dialog) { $dialog.Dispose() }
}