简体   繁体   中英

Powershell - SaveFileDialog creates txt file temporarily

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM