Clip.exe and the missing Paste.exe

0 Flares Twitter 0 Facebook 0 Google+ 0 Buffer 0 LinkedIn 0 Email -- StumbleUpon 0 0 Flares ×

One of the guys on #PowerShell in IRC was asking about how to get the contents of the clipboard in PowerShell, and after we had tried several different scripts, we realized that in Version 1, because PowerShell runs in an MTA thread, you cannot access the clipboard without creating a new thread (in STA mode). After I got done ranting, and pointing out that everyone needs to use PowerShell v2 (yeah, it’s still in CTP, so I was mostly kidding) in -STA mode … I whipped together the C# one liner and stuck it into a class with instructions for compiling, and figured I might as well share.

The code is below. There are two files: Clip.cs and Paste.cs … you probably only need Paste.cs, because Clip.exe is already included in Windows after Windows XP, but for the sake of completeness (and because it was just a few lines), I wrote them both.

To use them, you must compile them using Csc.exe, which is included as part of the .Net Framework. If it’s not already on your path, it’s in the folder for your most recent .Net Framework version (eg: C:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe or C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe). All you have to do is run: csc Paste.cs and csc Clip.cs and you should end up with a Paste.exe and Clip.exe which you can use to copy and paste from the command-line…

Paste.cs


using System;
using System.Windows.Forms;
using System.Threading;

namespace Huddled {
   public class Paste {
      [STAThread]
      static void Main( string[] args )
      {
         foreach(string line in Clipboard.GetText().Split(
                                 new string[]{"\r\n","\n"},
                                 StringSplitOptions.None ))
            Console.WriteLine( line );
      }
   }
}

Clip.cs


using System;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Huddled {
public class Clip {
   [STAThread]
   static void Main( string[] args )
   {
      string s;
      StringBuilder output = new StringBuilder( string.Join(" ", args) );
      while ((s = Console.ReadLine()) != null)
         output.AppendLine(s);

      Clipboard.SetText( output.ToString() );
   }
}
}

Similar Posts:

0 Flares Twitter 0 Facebook 0 Google+ 0 Buffer 0 LinkedIn 0 Email -- StumbleUpon 0 0 Flares ×