Skip to content

Instantly share code, notes, and snippets.

@Saturnous
Last active December 28, 2023 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Saturnous/10934e7ab86ba743953c2a208d122192 to your computer and use it in GitHub Desktop.
Save Saturnous/10934e7ab86ba743953c2a208d122192 to your computer and use it in GitHub Desktop.
Install-RoyalTS_UseSavedCred
<#
Using Assembly System.Windows
Using Assembly UIAutomationProvider
Using Assembly UIAutomationClient
Add-Type -TypeDefinition @"
using System;using System.Collections.Generic;using System.Runtime.InteropServices;public static class KBEmulator{public enum InputType:uint{INPUT_MOUSE=0,INPUT_KEYBOARD=1,INPUT_HARDWARE=3}[Flags]internal enum KEYEVENTF:uint{KEYDOWN=0x0,EXTENDEDKEY=0x0001,KEYUP=0x0002,SCANCODE=0x0008,UNICODE=0x0004}[Flags]internal enum MOUSEEVENTF:uint{ABSOLUTE=0x8000,HWHEEL=0x01000,MOVE=0x0001,MOVE_NOCOALESCE=0x2000,LEFTDOWN=0x0002,LEFTUP=0x0004,RIGHTDOWN=0x0008,RIGHTUP=0x0010,MIDDLEDOWN=0x0020,MIDDLEUP=0x0040,VIRTUALDESK=0x4000,WHEEL=0x0800,XDOWN=0x0080,XUP=0x0100}[StructLayout(LayoutKind.Sequential)]public struct lpInput{internal InputType type;internal InputUnion Data;internal static int Size{get{return Marshal.SizeOf(typeof(lpInput));}}}[StructLayout(LayoutKind.Explicit)]internal struct InputUnion{[FieldOffset(0)]internal MOUSEINPUT mi;[FieldOffset(0)]internal KEYBDINPUT ki;[FieldOffset(0)]internal HARDWAREINPUT hi;}[StructLayout(LayoutKind.Sequential)]internal struct MOUSEINPUT{internal int dx;internal int dy;internal int mouseData;internal MOUSEEVENTF dwFlags;internal uint time;internal UIntPtr dwExtraInfo;}[StructLayout(LayoutKind.Sequential)]internal struct KEYBDINPUT{internal short wVk;internal short wScan;internal KEYEVENTF dwFlags;internal int time;internal UIntPtr dwExtraInfo;}[StructLayout(LayoutKind.Sequential)]internal struct HARDWAREINPUT{internal int uMsg;internal short wParamL;internal short wParamH;}private class unmanaged{[DllImport("user32.dll",SetLastError=true)]internal static extern uint SendInput(int cInputs,[MarshalAs(UnmanagedType.LPArray)]lpInput[]inputs,int cbSize);[DllImport("user32.dll",CharSet=CharSet.Unicode,SetLastError=true)]public static extern short VkKeyScan(char ch);}internal static byte[]VkKeyScan(char ch){short keyCode=unmanaged.VkKeyScan(ch);if(keyCode>254){byte key=BitConverter.GetBytes(keyCode)[0];byte highByte=BitConverter.GetBytes(keyCode)[1];byte extraKey=0;switch(highByte){case 0x1:extraKey=0x10;break;case 0x2:extraKey=0x11;break;case 0x4:extraKey=0x12;break;}byte[]rtn=new byte[]{extraKey,key};return rtn;}else{byte[]rtn=new byte[]{BitConverter.GetBytes(keyCode)[0]};return rtn;}}internal static uint SendInput(int cInputs,lpInput[]inputs,int cbSize){return unmanaged.SendInput(cInputs,inputs,cbSize);}public static void SendKeyCode(byte[]keyCode){lpInput[]KeyInputs=new lpInput[keyCode.Length];for(int i=0;i<keyCode.Length;i++){lpInput KeyInput=new lpInput();KeyInput.type=InputType.INPUT_KEYBOARD;KeyInput.Data.ki.wScan=0;KeyInput.Data.ki.time=0;KeyInput.Data.ki.dwExtraInfo=UIntPtr.Zero;KeyInput.Data.ki.wVk=Convert.ToInt16(keyCode[i]);KeyInput.Data.ki.dwFlags=KEYEVENTF.KEYDOWN;KeyInputs[i]=KeyInput;}SendInput(keyCode.Length,KeyInputs,lpInput.Size);for(int i=0;i<keyCode.Length;i++){KeyInputs[i].Data.ki.dwFlags=KEYEVENTF.KEYUP;}SendInput(keyCode.Length,KeyInputs,lpInput.Size);return;}public static void SendCharacter(char ch){SendKeyCode(VkKeyScan(ch));return;}public static void SendString(string st){foreach(char ch in st.ToCharArray()){SendCharacter(ch);}}public static byte[]GetKeyCode(char ch){return VkKeyScan(ch);}}
"@
$MyParentProc=Get-Process -ID $(gwmi Win32_Process -Filter "ProcessID = ""$PID"" ").ParentProcessId
$RSAElement=[System.Windows.Automation.AutomationElement]::FromHandle($MyParentProc.MainWindowHandle)
$isPWFieldCondition=[System.Windows.Automation.PropertyCondition]::new([System.Windows.Automation.AutomationElement]::IsPasswordProperty,$true)
while($FoundElement.Count -ne 1) {Start-Sleep -Milliseconds 500;$FoundElement=$RSAElement.FindAll([System.Windows.Automation.TreeScope]::Subtree,$isPWFieldCondition)}
$FoundElement.SetFocus()
[KBEmulator]::SendString($args[0])
[KBEmulator]::SendKeyCode([byte[]]0xd)
#>
$code = Get-Content $MyInvocation.MyCommand.path
$scriptfolder = New-Item -ItemType Directory -path "$($env:APPDATA)\code4ward" -Force -Name "Scripts"
$code[1..13]|Out-File -FilePath "$($scriptfolder.FullName)\UseSavedCred.ps1"
get-process -Name RoyalTS|Stop-Process -Force
$XMLEntries = [xml]@"
<Data>
<RoyalFolder>
<ID>8919361f-e135-47ed-b8fc-723d7217d005</ID>
<Name>Tasks</Name>
<Modified>TIMESTAMPTOFILL</Modified>
<Created>TIMESTAMPTOFILL</Created>
<ModifiedBy></ModifiedBy>
<CreatedBy></CreatedBy>
<PositionNr>1</PositionNr>
<IsExpanded>True</IsExpanded>
<ParentID>ParentIDToFill</ParentID>
</RoyalFolder>
<RoyalCommandTask>
<ID>36453c76-e577-49c2-a29d-461f5d040dd0</ID>
<Name>UseSavedCred</Name>
<Modified>TIMESTAMPTOFILL</Modified>
<Created>TIMESTAMPTOFILL</Created>
<ModifiedBy></ModifiedBy>
<CreatedBy></CreatedBy>
<PositionNr>1</PositionNr>
<CommandLine>%systemroot%\System32\WindowsPowershell\v1.0\powershell.exe</CommandLine>
<Arguments>-ExecutionPolicy Bypass -Window Minimized -File "%appdata%\code4ward\Scripts\UseSavedCred.ps1" $EffectivePassword$</Arguments>
<WorkingDirectory />
<CommandLineOSX />
<ArgumentsOSX />
<WorkingDirectoryOSX />
<ColorFromParent>False</ColorFromParent>
<ColorName />
<Color />
<CustomImage />
<CustomImageName />
<CustomImageList>{}</CustomImageList>
<Description />
<NoConfirmationRequired>True</NoConfirmationRequired>
<ShowInFavoriteTasks>False</ShowInFavoriteTasks>
<Favorite>False</Favorite>
<CredentialUsername />
<CredentialPassword />
<CredentialId>00000000-0000-0000-0000-000000000000</CredentialId>
<CredentialName />
<CredentialMode>1</CredentialMode>
<RunAsCredential>False</RunAsCredential>
<LoadUserProfile>False</LoadUserProfile>
<ParentID>8919361f-e135-47ed-b8fc-723d7217d005</ParentID>
<ObjectSpecialUsage />
</RoyalCommandTask>
</Data>
"@
$RoyalTSProc=Get-Process -Name RoyalTS
$RoyalTSPath=$RoyalTSProc.path
$RoyalTSProc|Stop-Process -Force
$RTSSettings=[xml]$(Get-Content "$($env:APPDATA)\code4ward\code4ward.RoyalTS.UserPreferences.config")
$MainDoc=$RTSSettings.RTSZDocument.RoyalApplicationSetting.AutoStartDocumentList.Split(",")[0] -Replace("{|}","") -replace("\\\\","\")
Copy-Item -Path $MainDoc -Destination $($MainDoc -replace("$",".Bckup"))
$MainDocXML=[xml]$(Get-Content $MainDoc)
$MainDocXML.RTSZDocument.RoyalCommandTask.Where({$_.ID -in $XMLEntries.Data.ChildNodes.ID}).RemoveAll()
$XMLEntries.Data.RoyalFolder.ParentID = $MainDocXML.RTSZDocument.RoyalDocument.ID
$PositionNr=1
while($PositionNr * 2 -in $MainDocXML.RTSZDocument.RoyalFolder.Where({$_.ParentID -eq $MainDocXML.RTSZDocument.RoyalDocument.ID}).ForEach({[int]$_.PositionNr}) ){$PositionNr++}
$XMLEntries.Data.RoyalFolder.PositionNr = [string]$($PositionNr * 2)
$XMLEntries.Data.ChildNodes.ForEach({$_.Created = [datetime]::now.ToString("M/d/yyyy HH:mm:ss.fff",$([cultureinfo]"en_us")) })
$XMLEntries.Data.ChildNodes.ForEach({$_.Modified = [datetime]::now.ToString("M/d/yyyy HH:mm:ss.fff",$([cultureinfo]"en_us")) })
$XMLEntries.Data.ChildNodes.ForEach({$_.CreatedBy = [Security.Principal.WindowsIdentity]::GetCurrent().Name })
$XMLEntries.Data.ChildNodes.ForEach({$_.ModifiedBy = [Security.Principal.WindowsIdentity]::GetCurrent().Name })
$FolderXML=$MainDocXML.CreateElement("RoyalFolder")
$FolderXML.InnerXML = $XMLEntries.Data.RoyalFolder.InnerXml
$TaskXML=$MainDocXML.CreateElement("RoyalCommandTask")
$TaskXML.InnerXml = $XMLEntries.Data.RoyalCommandTask.InnerXml
$MainDocXML.RTSZDocument.InsertAfter($FolderXML,$MainDocXML.RTSZDocument.RoyalFolder[-1])
$MainDocXML.RTSZDocument.InsertAfter($TaskXML,$MainDocXML.RTSZDocument.RoyalFolder[-1])
$MainDocXML.Save($MainDoc)
$RoyalTSProc.ReFresh()
if($RoyalTSProc.HasExited){Start-Process -FilePath $RoyalTSProc.Path}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment