TIP: Two more PowerShell errors

Put simple Tips and Tricks that are not entire Tutorials in this forum
RickC
Posts: 302
Joined: 27 Oct 2013, 08:32

TIP: Two more PowerShell errors

Post by RickC » 14 Oct 2016, 15:24

If you wrap some PowerShell code in AHK and get "An attempt was made to load a program with an incorrect format" error when you run it, it means that you're trying to run, for example, a PowerShell code block using a 32-bit install of AHK in a 64-bit version of Windows.

I'm happy to be proved wrong but I believe the only way round this is to use the 64-bit version of the AHK installer.

Also, you may need to run PowerShell code elevated if you get a "The requested operation requires elevation" error within PowerShell.

So, for example, to display a formatted list of Optional Features and avoid these two errors I had to use the following after installing the 64-bit version of the AHK installler:

Code: Select all

; Prompt to 'Run as Admin', i.e. show UAC dialog
If Not A_IsAdmin
{
   Run *RunAs "%A_ScriptFullPath%"  ; Requires v1.0.92.01+
   ExitApp
}

psScript =
(
Get-WindowsOptionalFeature -Online |Sort -Property State |ft
)

; Use this call if you don't want to see PowerShell output
;RunWait PowerShell.exe -Command &{%psScript%} ,, hide

; Use this call if you want to see PowerShell output
Run powershell.exe -NoExit -Command %psScript%
(Note: I had to use Get-WindowsOptionalFeature instead of Install-WindowsFeature as the latter cmdlet is not yet available for Windows 10.)

Hope this helps...

lexikos
Posts: 9780
Joined: 30 Sep 2013, 04:07
Contact:

Re: TIP: Two more PowerShell errors

Post by lexikos » 15 Nov 2016, 03:36

There are two versions of PowerShell on x64 systems: "Windows PowerShell" and "Windows PowerShell (x86)".

The 64-bit one is in %A_WinDir%\System32 and the 32-bit one is in %A_WinDir%\SysWow64. The same goes for regedit and cmd.

For 32-bit processes on 64-bit Windows, the system redirects "System32" to SysWow64 and (on Vista and later) redirects "SysNative" to the real System32. So to run PowerShell x64 from AutoHotkey 32-bit, just take the full path of powershell.exe and replace "System32" with "SysNative" (but only if (A_PtrSize = 4 && A_Is64bitOS)).

Further reading: File System Redirector (Windows)

RickC
Posts: 302
Joined: 27 Oct 2013, 08:32

Re: TIP: Two more PowerShell errors

Post by RickC » 20 Nov 2016, 07:33

Thank you, lexicos. I posted this thread in 'Tutorials' because a) many of us are very much 'AHK beginners'... and I didn't want others to struggle in the same way that I did; and b) I couldn't see a more appropriate forum.

Unfortunately 'Tutorials' gives the impression of knowledge. I don't have that 'knowledge'... just the results of (trial and error) 'experience', which I hoped was useful to pass on to others trying to accomplish similar.

Post Reply

Return to “Tips and Tricks (v1)”