I am trying to directly call some Win32 API's from a PowerShell script. I managed to make WNetAddConnection work with the code below:
$cp = New-Object Microsoft.CSharp.CSharpCodeProvider
$cpar = New-Object System.CodeDom.Compiler.CompilerParameters
$Code = @"
using System;
using System.Runtime.InteropServices;
namespace Win32Api
{
public class Net
{
[DllImport("mpr.dll", EntryPoint = "WNetAddConnection")]
public static extern uint Map(string lpRemoteName, string lpPassword, string lpLocalName);
[DllImport("mpr.dll", EntryPoint = "WNetCancelConnection")]
public static extern uint Delete(string lpName, byte fForce);
}
}
"@
$cp.CompileAssemblyFromSource($cpar, $code)
[Win32Api.Net]::Map("\\REMKOLAPTOP\C$", $null, "W:")
Now I would like to do the same WNetAddConnection2, although I found the proper declarations for C# I am unsure how to declare this for usage in PowerShell. So my questions is: what is the proper "translation" and an example of calling the API would be great.
Please note that I do not want to use non api methods like the one below:
$net = $(New-Object -Com WScript.Network)
$net.MapNetworkDrive("u:", "\\computer\share")
I was able to get the following code working on PowerShell 2.0. Note that I also use one PSCX (http://pscx.codeplex.com) function that just converts a Windows error code into a message. I also setup the options to do an interactive prompt for username and password. Commented out script is included that shows how you could do the same using PowerShell's Get-Credential cmdlet.
BTW if you supply the username/password via variables to the function be sure to get the order right, it is password followed by username. That bit me for 10 minutes until I finally figured out I had the order wrong. Doh! One other tidbit, for interop help like this be sure to checkout http://www.pinvoke.net. Anyway, hope this helps.