我正在编写一个控制 docker 容器的服务。我希望将安装的卷作为 Azure 共享,因此需要使用 SMB 全局映射。如果我使用通常的 WNetAddConnection2A,那么我可以在代码中很好地挂载共享,但容器无法看到它,因为它不是“全局”的。我找不到 PowerShell New-SmbGlobalMapping 命令的源代码(有办法查看它吗?),也找不到合适的 API 来调用。我希望有人知道我可以放入 .NET 代码中的魔法。
最佳答案
I can't find source for the PowerShell New-SmbGlobalMapping command (is there a way to see it?) and I can't find a suitable API to call. I hope someone knows the magic incantation I can put in my .NET code.
PowerShell 使用WMI
就你而言,它调用 Create method of the MSFT_SmbMapping类(MSFT_SmbGlobalMapping 完全一样)
您可以使用WMI Code Creator生成/测试 C# 代码
编辑:使用 PowerShell.Create 进行测试
- 在 Windows 10 上以管理员身份进行测试( list 中的“requireAdministrator”)
- 测试代码(C#、VS 2015)=>
// PowerShell calls CredUIPromptForCredentialsW to display the User/Password dialog (you can call it with P/Invoke if needed)
string sUser = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="31444254437141435e47585554431f525e5c" rel="noreferrer noopener nofollow">[email protected]</a>";
string sPassword = "myPassword";
System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(sUser, sPassword, null);
System.Security.SecureString securePassword = new System.Security.SecureString();
foreach (var c in networkCredential.Password)
securePassword.AppendChar(c);
// Add reference to :
// C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll
// Add :
// using System.Management.Automation;
PSCredential psCredential = new PSCredential(networkCredential.UserName, securePassword);
// Error handling must be improved : if I pass an invalid syntax for "RemotePath" or not launched as Admin,
// nothing happens (no error, no result) (on Windows 10)
string sLocalPath = "Q:";
string sRemotePath = "\\\\DESKTOP-EOPIFM5\\Windows 7";
using (var ps = PowerShell.Create())
{
ps.AddCommand("New-SmbGlobalMapping");
ps.AddParameter("LocalPath", sLocalPath);
ps.AddParameter("RemotePath", sRemotePath);
ps.AddParameter("Credential", psCredential);
//ps.AddParameter("RequireIntegrity", false);
//ps.AddParameter("RequirePrivacy", false);
try
{
System.Collections.ObjectModel.Collection<PSObject> collectionResults = ps.Invoke();
foreach (PSObject psObl in collectionResults)
{
Console.WriteLine("Status : {0}", psObl.Members["Status"].Value.ToString());
Console.WriteLine("Local Path : {0}", psObl.Members["LocalPath"].Value.ToString());
Console.WriteLine("Remote Path : {0}\n", psObl.Members["RemotePath"].Value.ToString());
}
}
catch (ParameterBindingException pbe)
{
System.Console.WriteLine("\rNew-SmbGlobalMapping error : {0}: {1}",
pbe.GetType().FullName, pbe.Message);
}
}
// To get and remove the test mapping in PowerShell :
// Get-SmbGlobalMapping
// Remove-SmbGlobalMapping -RemotePath "\\DESKTOP-EOPIFM5\Windows 7" -Force
关于powershell - 如何在 C# 代码中复制 New-SmbGlobalMapping?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850998/