Home > Back-end >  Trying to shorten this block of code as much as possible using code golfing etc
Trying to shorten this block of code as much as possible using code golfing etc

Time:11-17

I have the following fun little script used to have a user automatically subscribe to a youtube channel, just trying to see how far someone can dwindle this code down

Ex: using -AssemblyName *m.W*s.F*s instead of -AssemblyName System.Windows.Forms

Add-Type -AssemblyName System.Windows.Forms;
$o=New-Object -ComObject WScript.Shell;
Saps https://www.youtube.com/CHANNEL-NAME?sub_confirmation=1;
Sleep 3;
[System.Windows.Forms.SendKeys]::SendWait('{TAB}'*2);
[System.Windows.Forms.SendKeys]::SendWait('{ENTER}');
Sleep 1;
[System.Windows.Forms.SendKeys]::SendWait('%{F4}')

CodePudding user response:

Cut -AssemblyName to -a, as long as the prefix is unique it will match.

On mine s*ms matches only System.Windows.Forms.

You could cut -ComObject to the shortest unique prefix -c, but you aren't using the WScript.Shell object so drop that line.

Drop www. from the YouTube URL

Merge the two Tabs and Enter to remove one of the SendWait lines.

Drop [System. from the type names.

Store the SendKeys bit for reuse shorter.

I've dropped the ; but they need to come back for it to be on one line.

add-type -a s*ms
saps https://youtube.com/CHANNEL-NAME?sub_confirmation=1
($w=[Windows.Forms.SendKeys])::SendWait('{TAB}{TAB}{ENTER}')
sleep 1
$w::SendWait('%{F4}')

I think that's as short as it easily gets, it's possible to store SendWait as well, but then you need .Invoke() which pads it out again. There's no default aliases for add-type or new-object.

If you could swap for WScript.Shell SendKeys:

$w=New-Object -c wscript.shell
saps https://youtube.com/CHANNEL-NAME?sub_confirmation=1
$w.SendKeys('{TAB}{TAB}{ENTER}')
sleep 1
$w.SendKeys('%{F4}')
  • Related