Cmdlet file dialog implementation

ptxof8fRUH 1 Reputation point

I have a console application in .NET 6 that hosts Powershell cmdlets using System.Management.Automation. I'm trying to make the cmdlet open up a file dialog inside the ProcessRecord method of the PSCmdlet but I haven't found a way to do this after an extensive search. I tried OpenFileDialog which comes from Windows Forms but it only works in the host. I would like it to be launched from within the cmdlet class. But calling ShowDialog throws this exception`ThreadStateException:

'Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThhreadAttribute marked on it. This exception is only raised if a debugger is attached to the process'`

and I do have the STAThread attribute on the host's Main.

So I would like to ask how exactly you go about implementing this.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,407 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 39,436 Reputation points


    Thank you for posting your query.

    Kindly follow the steps provided below to resolve your issue.

    You want the OpenFileDialog class

    This class allows you to check whether a file exists and to open it

    Do not hesitate to message us if you need further assistance.


    If the answer is helpful kindly click "Accept as Answer" and upvote it. Thanks.

    0 comments No comments