且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#运行空间中的其他远程服务器上运行远程Powershell脚本

更新时间:2023-10-21 16:11:46

我从来没有直接使用它,这似乎是一种安全性功能",您无法在远程工作时使用UNC地址访问第三台计算机. .但是,我能够找到一种对我有用的解决方法.

I never did get this to work directly and seems to be a security "feature" that you can't access a third machine using a UNC address while working remotely. I was however able to find a workaround that worked great for me.

我没有尝试直接调用\\ server \ share地址,而是动态地将要运行脚本的计算机上的网络驱动器映射到具有该脚本的计算机上的共享. (从A远程运行,将B上的驱动器映射到C上的共享).然后,我通过该驱动器调用脚本,它就像一个符咒一样工作.这是我传递给上面的RunRemoteScript方法的字符串:

Instead of trying to call directly to a \\server\share address, I dynamically map a network drive on the machine I'm trying to run the script against to a share on the machine that has the script. (Running remotely from A, map a drive on B to a share on C). Then I call my scripts through that drive and it works like a charm. This string is what I pass in to the RunRemoteScript method above:

"$net = new-object -ComObject WScript.Network;" +
"if(!($net.EnumNetworkDrives() -contains \"S:\"))" +
    "{Write-Host \"S: Drive Not Currently Mapped. Mapping to \\\\" + RemoteServerC + "\\Share.\";" +
    "$net.MapNetWorkDrive(\"S:\",\"\\\\" + RemoteServerC + "\\Share\",$false,\"username\",\"password\")};" +
"Get-PSDrive | Write-Verbose;" +
"& \"S:\\PathToScript\\Install.ps1\" -noPrompt;"

RemoteServerC是我传入的在用户配置文件中定义的变量.

RemoteServerC is a variable I pass in that is defined in a user config file.

如果有人需要的话,这里的代码与powershell脚本的代码相同(将RemoteServerC替换为您需要先设置的powershell变量,或者只是硬编码:

Here is the same code as just powershell script if anyone needs it (replacing RemoteServerC with a powershell variable you'd need to set before or just hardcode:

$net = new-object -ComObject WScript.Network
if(!($net.EnumNetworkDrives() -contains "S:"))
{  Write-Host "S: Drive Not Currently Mapped. Mapping to \\remoteserverC\Share."
   $net.MapNetWorkDrive("S:","\\remoteserverC\Share",$false,"username","password")
}
Get-PSDrive | Write-Verbose
& "S:\\PathToScript\\Install.ps1\" -noPrompt;"

首先,我将对象设置为能够映射驱动器.然后,我检查远程计算机上是否已经映射了"s"驱动器.如果还没有,则使用我们在活动目录中设置的名称和密码将共享映射到远程计算机上的"s"驱动器上.

First I set up the object to be able to map the drive. I then check if there is already an "s" drive mapped on the remote machine. If it hasn't I then map the share to the "s" drive on the remote machine using a name and password we set up in active directory to run this service.

我包括了Get-PSDrive命令,因为它似乎迫使Powershell重新加载可用驱动器列表.这似乎只在您第一次尝试在Powershell会话中运行时才有意义(通过c Sharp,我不知道它是否确实有必要,为了安全起见,我将其包括在内).如果使用MapNetworkDrive,则Powershell显然无法在创建的同一会话中识别出驱动器添加.

I included the Get-PSDrive command because it appears to force powershell to reload the list of available drives. This seems to only matter the very first time you try to run this in a powershell session (and through c sharp I don't know if it is truly necessary or not, I included it to be safe). Apparently powershell does not recognize a drive addition in the same session it was created if you use MapNetworkDrive.