Reputation: 220
For some reason this script does not work in this code:
public class PowerShellTest
{
public void Execute()
{
string scriptText = "$F = [System.Windows.Forms.Clipboard]::GetFileDropList(); $F;";
//string co = "\"D:\\\"";
//co = "$Dirs = [System.IO.Directory]::GetDirectories(" + co + "); ";
//co = co + " $Dirs;";
//scriptText = co;
using( PowerShell ps = PowerShell.Create() )
{
ps.AddScript(scriptText, true);
var x = ps.Invoke();
}
}
}
The issue is that it doesn't return anything and the PSObject
collection count is 0
.
However it works when I run it in the PowerShell ISE.
Any suggestions?
Upvotes: 1
Views: 218
Reputation: 119836
To access the clipboard you need to ensure your PowerShell instance starts in STA
or Single Threaded Apartment mode and also make sure you've referenced the System.Windows.Forms
assembly.
To do this:
string scriptText = @"
Add-Type -an System.Windows.Forms | Out-Null;
$f = [System.Windows.Forms.Clipboard]::GetFileDropList();
$f;
";
using (PowerShell ps = PowerShell.Create())
{
PSInvocationSettings psiSettings = new PSInvocationSettings();
psiSettings.ApartmentState = System.Threading.ApartmentState.STA;
ps.AddScript(scriptText, true);
var x = ps.Invoke(null, psiSettings);
}
If you were trying to do this directly from a .NET Console application you'd need to do the same thing:
class Program
{
[STAThread]
static void Main(string[] args)
{
var f = System.Windows.Forms.Clipboard.GetFileDropList();
Console.WriteLine(f.Count);
}
}
Upvotes: 1
Reputation: 4742
PowerShell ISE loads the Windows Forms type automatically, but the PowerShell command line doesn't. Use the following line in the script before you try to do anything with the clipboard object.
add-type -an system.windows.forms
Upvotes: 1