2012-09-19 308 views
1

在当前机器 上执行脚本下面的代码适用于执行脚本(目前,该脚本是一个简单的消息框显示传入的参数)远程服务器

Arguments: 

UserName = Nothing 
Password = Nothing 
RemoteMachineName = "CurrentMachineName" 
PathBashFile = "Path/To/My/Local/Script.ps1" 
Params = "parameter1" 

然而,当我想在远程计算机上运行本地脚本,脚本为从不执行。该代码不会抛出任何异常。

Arguments: 

UserName = "MyUsername" 
Password = "MyPassword" 
RemoteMachineName = "RemoteMachineName" 
PathBashFile = "Path/To/My/Local/Script.ps1" 
Params = "parameter1" 

所有我的结果是:

outParams("processId") = Nothing 
outParams("returnValue") = 8 

这是怎么回事?为什么我的脚本没有按预期在远程机器上运行? (没有消息框弹出无论是机器,我已经尝试过其他的cmdlet,但没有以往任何时候都工作)。

下面是代码:

Try 
    connOptions = New ConnectionOptions() 
    connOptions.Username = UserName 
    connOptions.Password = Password 

    connOptions.Impersonation = ImpersonationLevel.Impersonate 
    connOptions.Authentication = Management.AuthenticationLevel.PacketPrivacy 

    managementPath = New ManagementPath("\\" & RemoteMachineName & "\root\cimv2:Win32_Process") 

    Scope = New ManagementScope(managementPath, connOptions) 
    Scope.Connect() 
    objectGetOptions = New ObjectGetOptions() 
    processClass = New ManagementClass(Scope, New ManagementPath("root\cimv2:Win32_Process"), objectGetOptions) 

    inParams = processClass.GetMethodParameters("Create") 
    inParams("CommandLine") = "cmd.exe /c powershell """ & PathBashFile & """ " & params 
    inParams("CurrentDirectory") = workingDirectoryPath 
    outParams = processClass.InvokeMethod("Create", inParams, Nothing) 
    MsgBox(outParams("processId") & " " & outParams("returnValue")) 

Catch ex As Exception 
    Throw New Exception("[ExecuteRemoteBashFile] " & ex.Message) 
End Try 

如果有人能在我的代码,指出任何错误,它会非常感谢!

+0

你确定你需要PRIVS,和用户权限(如执行批处理脚本“或类似)在远程机器上?(我不确定是否有这些会导致在这种情况下抛出异常,说实话...我会这样想,但我想我应该建议它以防万一...) – Sepster

+0

那么,如果我在另一台服务器本地运行脚本,它可以很好地工作 – Msonic

+0

为什么不使用WS管理(考虑到您至少使用Powershell v2) ?你会避免与W打交道MI直接。检查http://technet.microsoft.com/en-us/magazine/ff700227.aspx –

回答

0

我解决我的问题通过将完整路径powershell.exe,而不是假设控制台知道在何处寻找那些...

inParams("CommandLine") = "cmd.exe /c C:\Windows\System32\WindowsPowerShell\v2.0\powershell.exe """ & PathBashFile & """ " & params