I want to import the dll with the relative path in powershell. Below is the code snippet that I am trying to import dll.
$dirpath = split-path $MyInvocation.MyCommand.Definition
$testDllPath = "$dirpath\..\Test1\Test.dll"
$signatureGet = @'
[DllImport(@"$testDllPath",EntryPoint="TestMethod",ExactSpelling=false)]
public static extern bool TestMethod([MarshalAs(UnmanagedType.LPWStr)]string args1, [MarshalAs(UnmanagedType.LPWStr)]string args2);
'@
$typeFunc = Add-Type -MemberDefinition $signatureGet -Name "TestMethod" -PassThru
$ret = $typeFunc::TestMethod($args1, $args2)
When I try the same with the hardcoded path it is able to load the dll. The same with the relative path it is not working. Its throwing the error for incorrect format.
Please let me know how to achieve this.
Relying on the current directory (by using a relative path) in PowerShell is dangerous when interop'ing with Windows. For example, if you execute this sometime:
[environment]::CurrentDirectory
You will see that PowerShell's notion of current directory doesn't always match the Windows notion of current directory. This is because you can have multiple scripts running simultaneously in the same PowerShell process and they can each change the current dir as needed. Besides I don't think the DllImportAttribute accepts a relative path to start with. It is usually supplied just a name and then Windows searches the same dir as the exe (PowerShell.exe) then paths in the PATH environment variable.
What you can do is modify the $env:PATH env var just before you attempt to call the script that imports the dll e.g:
$dirpath = split-path $MyInvocation.MyCommand.Definition
$env:PATH += ";$dirpath\..\..\Test1"
$signatureGet = @'
[DllImport(@"Test.dll",EntryPoint="TestMethod",ExactSpelling=false)]
public static extern bool TestMethod([MarshalAs(UnmanagedType.LPWStr)]string args1, [MarshalAs(UnmanagedType.LPWStr)]string args2);
'@
$typeFunc = Add-Type -MemberDefinition $signatureGet -Name "TestMethod" -PassThru
$ret = $typeFunc::TestMethod($args1, $args2)