简体   繁体   中英

Using to get PS script name from a C# DLL? Getting "Object reference not set to an instance of an object."

ERROR:

Object reference not set to an instance of an object.

I'm trying to create a DLL that can get the Entrypoint application name that is written in Powershell.

The layout is very simple:
In Powershell I add the line

Add-Type -Path ('C:\Users\Public\PS\DLL\get_value.dll')

then I create the object

$value = New-Object PS_get_value.Stack

and call the C# method

$rtn = $value.Get_stack()

If the Get_stack() method returns a basic string like "Test" it works fine…. BUT if I try to use the .net Assembly. GetEntryAssembly().Location (which should return the full path to the calling (parent) app), I get the error above.

I am trying to get the full path (or at least the filename) of the application script that is running in Powershell. I plan on using that value to validate that the program (PS script) is the one that should be running. If there is a different way for the C# code to get it that's fine. BTW if I run a normal program it works. I do know that there is something about managed code base, I'm not sure what that is.
Thanks for any help or direction your can give.

Code Example:
PS:

Add-Type -Path ('C:\Users\Public\PS\DLL\get_value.dll')
$addNum = New-Object PS_get_value.Stack
$_rtnKey = $addNum.Get_stack()
Write-Host "RTNed Key Version 2: $_rtnKey"

C# (the DLL):

using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;

namespace PS_get_value
{
    public class Stack{
      public string Get_stack()
        {
            string _test_a = g_stack();
            return _test_a;
        }

      public string g_stack()
        {
            return System.Reflection.Assembly.GetEntryAssembly().Location;
        }
   }
}

Give it a try by returning one of the following:

  1. Assembly.GetExecutingAssembly().Location

or

  1. Assembly.GetExecutingAssembly().CodeBase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM