1

The method GetActiveObject() is available in System.Runtime.InteropServices.Marshal in .NET Framework, but not in .NET Core (https://stackoverflow.com/a/58010881/180275).

Is there a way around if I want to use .NET Core (from PowerShell 7)?

René Nyffenegger
  • 37,844
  • 31
  • 151
  • 262

2 Answers2

3

Here is an equivalent implementation that works for .NET core 3.1+ on Windows (and .NET framework):

public static object GetActiveObject(string progId, bool throwOnError = false)
{
    if (progId == null)
        throw new ArgumentNullException(nameof(progId));

    var hr = CLSIDFromProgIDEx(progId, out var clsid);
    if (hr < 0)
    {
        if (throwOnError)
            Marshal.ThrowExceptionForHR(hr);

        return null;
    }

    hr = GetActiveObject(clsid, IntPtr.Zero, out var obj);
    if (hr < 0)
    {
        if (throwOnError)
            Marshal.ThrowExceptionForHR(hr);

        return null;
    }
    return obj;
}

[DllImport("ole32")]
private static extern int CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid lpclsid);

[DllImport("oleaut32")]
private static extern int GetActiveObject([MarshalAs(UnmanagedType.LPStruct)] Guid rclsid, IntPtr pvReserved, [MarshalAs(UnmanagedType.IUnknown)] out object ppunk);

I'm not a Powershell expert, but I think you can port that to Powershell or use a bit of C# directly in Powershell.

Simon Mourier
  • 123,662
  • 18
  • 237
  • 283
  • 2
    Awesome thanks for this. To get to this in powershell you can use Add-Type. Add the above script into a $methodDef variable and do something better than this ```$blah = add-type -MemberDefinition $methodDef -Name "Blah" -Namespace "Blah" -PassThru``` then use it as ```$dte = $blah::GetActiveObject('VisualStudio.DTE.16.0')``` [More information on Add-Type here](https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-1/) – Brett Oct 16 '21 at 18:28
0

That specific API is gone, but you can easily P/Invoke GetActiveObject to get that information.

Blindy
  • 60,429
  • 9
  • 84
  • 123