سؤال

I want to show a File Dialog from VBScript, and I'd like to use PowerShell.

How can I use this PowerShell code with CreateObject("WScript.Shell").Exec() to get the PowerShell output with the StdOut property?

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = "C:\"
$OpenFileDialog.filter = "|*.*"
$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
هل كانت مفيدة؟

المحلول

Well, I think I did it. Haven't seen this method anywhere before.

I'm scripting for Windows 8, and other methods are not available, or elegant.

Function OpenFileDialog(sDir, sFilter, sTitle)
    With Createobject("Scripting.FileSystemObject")

        If .FileExists("OUTPUT") Then .DeleteFile("OUTPUT")

        CreateObject("WScript.Shell").Run _
            "powershell.exe -command ""& {"& _
                "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null;"& _
                "$o = New-Object System.Windows.Forms.OpenFileDialog;"& _
                "$o.InitialDirectory = '"& sDir &"';"& _
                "$o.Filter = '"& sFilter &"';"& _
                "$o.Title = '"& sTitle &"';"& _
                "$o.ShowDialog() | Out-Null;"& _
                "$o.filename > OUTPUT"& _
            "}""",0

        Do
            WScript.Sleep 100
        Loop While Not .FileExists("OUTPUT")

        With .OpenTextFile("OUTPUT", 1, False, -1)
            Do While .AtEndOfStream
                WScript.Sleep 100
            Loop
            OpenFileDialog = .ReadLine
        End With

        .DeleteFile("OUTPUT")

    End With
End Function    

msgbox(OpenFileDialog("D:\", "|*.*", ""))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top