Convert short script to 1liner (-command format)

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Péter Stork Péter Stork 1 year, 11 months ago.

  • Author
    Posts
  • #21781
    Profile photo of Péter Stork
    Péter Stork
    Participant

    Hello guys,

    This will be an easy one for you I suppose.
    I'm having trouble converting one of my short scripts to match the format required by the -command parameter.
    The script is:

    Add-Type -TypeDefinition '
    using System;
    using System.Runtime.InteropServices;
     
    namespace Utilities {
       public static class Display
       {
          [DllImport("user32.dll", CharSet = CharSet.Auto)]
          private static extern IntPtr SendMessage(
             IntPtr hWnd,
             UInt32 Msg,
             IntPtr wParam,
             IntPtr lParam
          );
     
          public static void PowerOff ()
          {
             SendMessage(
                (IntPtr)0xffff, // HWND_BROADCAST
                0x0112,         // WM_SYSCOMMAND
                (IntPtr)0xf170, // SC_MONITORPOWER
                (IntPtr)0x0002  // POWER_OFF
             );
          }
       }
    }
    '
    [Utilities.Display]::PowerOff()
    

    Originally from http://www.powershellmagazine.com/2013/07/18/pstip-how-to-switch-off-display-with-powershell/
    If you want to test, it just turns your display off.
    Appreciate your help!

  • #21782
    Profile photo of Daniel Krebs
    Daniel Krebs
    Participant

    You will need to encode your script as Base64 and supply it to the EncodedCommand parameter of PowerShell.exe.

    Note: I have replaced SendMessage with SendNotifyMessage because SendMessage is waiting for the message to be processed which does not work for power off.

    Below example will encode the script and use the clip.exe to copy it into the Windows clipboard:

    $Command = @"
    Add-Type -TypeDefinition '
    using System;
    using System.Runtime.InteropServices;
     
    namespace Utilities {
       public static class Display
       {
          [DllImport("user32.dll", CharSet=CharSet.Auto)]
          private static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam);
     
          public static void PowerOff ()
          {
             SendNotifyMessage(
                (IntPtr)0xffff, // HWND_BROADCAST
                0x0112,         // WM_SYSCOMMAND
                (UIntPtr)0xf170, // SC_MONITORPOWER
                (IntPtr)0x0002  // POWER_OFF
             );
          }
       }
    }
    '
    [Utilities.Display]::PowerOff()
    "@
    
    $EncodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Command))
    'PowerShell.exe -EncodedCommand "{0}"' -f $EncodedCommand | clip
    

You must be logged in to reply to this topic.