使用vb.net连接远程PowerShell

时间:2014-06-20 12:39:31

标签: vb.net powershell

我在vb.net中编码并连接到远程PowerShell以执行命令。简单命令工作正常,但具有循环的复杂命令无法执行。  抛出异常:"在受限语言模式或数据部分中不允许使用脚本块文字。"请帮忙..无法找到任何问题。

  Public Function RemotePowerShell(username, securepassword, uri, connectionInfo)
    Dim powershell1 As PowerShell
    Dim creds As New PSCredential(username, securepassword)
    Dim runspace As Runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo)
    Try
          runspace.Open()

        'invoke the powershell to obtain the results
        Dim result As Collection(Of PSSession) = powershell1.Invoke(Of PSSession)()


        For Each current As ErrorRecord In powershell1.Streams.[Error]
            Console.WriteLine(("The following Error happen when opening the remote Runspace: " & current.Exception.ToString() & " | InnerException: " & current.Exception.InnerException)

        Next

        If result.Count <> 1 Then
            Throw New Exception("Unexpected number of Remote Runspace connections returned.")
        End If

        ' Set the runspace as a local variable on the runspace
        powershell1 = PowerShell.Create()
        ' associate the runspace with powershell
        powershell1.Runspace = runspace

        Dim Command = New PSCommand()
 ' this line which has $_ causing the problem 
        Command.AddScript("get-mailbox -identity 'SomeName'| Get-MailboxPermission | ?{($_.IsInherited -eq $False) -and -not ($_.User -match ""NT AUTHORITY"")}")
        powershell1.Commands = Command
        powershell1.Runspace = runspace
        Dim results As New Collection(Of PSObject)

        results = powershell1.Invoke()
    Catch ex As Exception

    Finally
        runspace.Dispose()
        runspace = Nothing

        'Finally dispose the powershell and set all variables to null to free up any resources.
        powershell1.Dispose()
        powershell1 = Nothing
    End Try
End Function

1 个答案:

答案 0 :(得分:0)

当我使用管道并设置命令Set-ExecutionPolicy RemoteSigned

时,它对我有用