Home > Software design >  Powershell - SaveFileDialog creates txt file temporarily
Powershell - SaveFileDialog creates txt file temporarily

Time:06-22

I want to create a GUI in Powershell where the user selects a path to save an empty txt file. For this I use SaveFileDialog. When I run the code below, the file is created temporarily. It is not saved permanently. What do I need to change?

Function fileSave
{
$OpenFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$OpenFileDialog.CheckPathExists = $true
$OpenFileDialog.CreatePrompt = true;
$OpenFileDialog.OverwritePrompt = true;
$OpenFileDialog.initialDirectory = $initialDirectory
$Directory = $OpenFileDialog.FileName = 'NewFile'
$OpenFileDialog.Title = 'Choose directory to save the output file'
$OpenFileDialog.filter = "Text documents (.txt)|*.txt"

# Show save file dialog box
if($OpenFileDialog.ShowDialog() -eq 'Ok'){
    $NewFile = New-Item -Path "$Directory" -ItemType File -Force
}

CodePudding user response:

You want to reference the FileName property inside your if condition, it will be the absolute path of the file to be created. Aside from that, you're using true instead of $true.

Add-Type -AssemblyName System.Windows.Forms

Function fileSave {
    $saveFileDialog = [System.Windows.Forms.SaveFileDialog]@{
        CheckPathExists  = $true
        CreatePrompt     = $true
        OverwritePrompt  = $true
        InitialDirectory = [Environment]::GetFolderPath('MyDocuments')
        FileName         = 'NewFile'
        Title            = 'Choose directory to save the output file'
        Filter           = "Text documents (.txt)|*.txt"
    }

    # Show save file dialog box
    if($saveFileDialog.ShowDialog() -eq 'Ok') {
        New-Item -Path $saveFileDialog.FileName -ItemType File -Force
    }
}

fileSave
  • Related