none
Connect to PSSession RRS feed

  • Question

  • Hi everyone!

    I´m trying, if its possible to execute a bunch of commands to get information from Exchange 2010 .

    What i´m trying to do, is to create a powershell process, load exchange modules in that powershell session and left the powershell open and running with all modules loaded.

    Then, when i have to execute another command, i´m trying to connect to that powershell session, that already have exchage modules loaded, and execute the command but all tests i have made doesnt worked like i expected.

    I already tryed create a new-pssession and when i open a new powershell process, i could connect to that session and i don´t know why.

    Anyone could help?

    Ty!

    MCP Windows XP / MCP ISA 2004 - Não esqueca de avaliar a resposta!

    Thursday, May 8, 2014 12:26 PM

Answers

  • OK, if you're just documenting states, that's a different scenario than what was presented.  

    Everything you're wanting to accomplish can be done through the remote management sessions provided by the Exchange servers, without using the snapin.  Once you are connected to that remote session, you can run the Exchange cmdlets you need either by using Invoke-Command directed at that session, or by importing the session.  

    If you can get past the idea that those commands are only available through the snapin and use the remote sessions you eliminate the problems of the system overhead involved in loading the snapin, along with the maintenance headache of keeping it updated every time a new CU gets applied to the Exchange servers.


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Thursday, May 8, 2014 8:54 PM
    Moderator
  • YOu will likely find that you cannot easily run an exchange shell under a service process.  YOu will also find trhat remoting weven on the same server is the easiest way to access exchange with no issues.  In other words do not rty to use th esnapin.

    If you need to use arbitrary commands over time a C#, VB,Net or other Net program can host PowerShell and open a permanent session.  This wil lbe internal to the service and it can be designed to load and execute arbitrary commands.  This would be the recommended method.  This will eliminate the reloading of PowerShell and Exchaneg and will allow for scripts to be designed and executed when necessary.

    In many ways the task scheduler would be better fo rthis if you are just gather information.

    For tightly couples needs you should really instrument exchange internally .  Exchange has an even model and an API that allow it to be extended.  Thisis how vendors work with Exchange.

    In the end you will have to learn how to use PowerShell and how to solve these design issues. We cannot really be of much help.

    We can answer specific questions.

    This comment makes no sense in the light of all other things you have posted.

    "And what if (not in this case because Exchange store information on AD) you lost your server and you need to know how something is configured before the server crash?"

    I would recommend backing up Active Directory daily.

    You can extract some items from AD but that does not require any of the issues you have posed.  Just write a script and run it.  You can read AD settings without loading the Exchange Shell.

    Exchange also has tools for dumping the configuration that you might want to use.


    ¯\_(ツ)_/¯

    Thursday, May 8, 2014 8:57 PM

All replies

  • There are a few ways to connect to Exchange through a 'regular' PS CLI.

    Here's how to remotely connect to it from another machine:

    $connectExchange = "http://mail.yourdomain.com/PowerShell/"
    # We will need to access Exchange, we will connect remotely for (Exchange 2010 requirement)
    # Note that this needs 'Set-User [service or user AD account] -RemotePowerShellEnabled $True' to be set on the Exchange server.
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectExchange -Authentication Kerberos
    Import-PSSession $Session -ErrorAction silentlycontinue

    ---

    and here is how you can 'connect' from another 'regular PowerShell CLI' on the Exchange server:

    add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010


    Regards, Paul www.servercare.nl

    • Proposed as answer by jrv Thursday, May 8, 2014 2:19 PM
    Thursday, May 8, 2014 12:33 PM
  • OK i understand that, but in my case the problem isnt how to connect to Exchange, the problem is how to connect to an existing powershell instance :/

    Thanks for the quick answer.

    Guilherme Hoscher

    Thursday, May 8, 2014 12:41 PM
  • Can you try & explain the problem behind this in some more detail, in other words, what are you attempting to accomplish exactly?

    Rather than already working on a proposed solution, it may help to present the exact challenge you are facing. Maybe there is another way to accomplish what you want to do. It would also help us understand the problem better.

    (If you want to connect to an already remotely opened session; I don't think that will work. Are you connecting remotely, or locally on the server?)


    Regards, Paul www.servercare.nl

    Thursday, May 8, 2014 12:51 PM
  • Well i will trying to explain.

    I working on a project that collect a series of attributes from Exchange and to collect all of this attributes the ideia is to use powershell commands that exist on Exchange PSSnapin.
    Well..... for example....one of the attributes that i trying to enumerate is the Exchange roles installed on a particular server.
    To get that information, i open powershell, load pssnapin and execute get-exchangeserver blablabla.
    Then, when i need to get another attribute.....i have to do the same thing again, and if i have to collect 100 attributes, the server load will grow up to high because every time i have to load Exchange module.

    This is the cenario, and.... i have to collect each attribute one by one because doing this, i know if one of them as changed, what attribute has changed and, the previous value of that attribute as the new one.

    So the ideia is to open 1 powershell, load modules and then redirect all commands to that session, eliminating the "load modules" problem.

    I hope it helps, and sorry about the bad english!

    Ohh...and this will be executed locally on the server.


    Guilherme Hoescher


    Thursday, May 8, 2014 1:08 PM
  • You only need to load the modules once.

    Using the remote connection you only need to import the session once.

    I think you need to go back and study what PowerShell is doing.  Somewhere you understanding is faulty and that is leading you to try and do things in this very odd way.


    ¯\_(ツ)_/¯

    Thursday, May 8, 2014 2:19 PM
  • Maybe you right!

    First of all, i not using a remote connection, the commands is processed locally by the server.

    Well think about this way..... what happen when you need to execute a bunch of commands when each of them by his own..

    You have to execute get-exchangeserver balblab record some returned value and then execute get-mailboxdatabase and record but all of this commands is executed on by one, and not in a script or in a active powershell window.

    The environment is a .net agent installed on local server that has list of attributes to monitor, and each attribute have his own command to get his value, so each command have to load exchange snappin and thats the problem.

    So the ideia is to run powershell and load exchange modules, then when each of the commands have to run, powershell connect to that other instance of powershell and run the needed command.

    Something like.....
    When the local agent starts it run..."powershell.exe -add-pssnapin exchange.....; new-psssession"
    When the agent need to run get-exchangeserver it starts "powershell.exe enter-pssession; get-exchangeserver;exit-pssession;exit"

    Doing this, the ideia is that the first powershell will keep running waiting for another command.

    Thats my ideia, but if someone could point me to another direction with the same behavior, thats ok!

    Thanks for help!

    Guilherme Hoescher

    Thursday, May 8, 2014 5:58 PM
  • Actually, you don't have to load the snapin or import the session at all.  

    If you're only executing a single command, all you have to do is establish the session , and then use Invoke-Command to run it in that remote session.  Import-PSSession is convenient for getting scripts that were written for an EMS shell to work with remoting, or for interactive work so that you get tab-completion on the commands and parameters, but it's a lot of unnecessary overhead in a script that's only going to use one command.


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "


    Thursday, May 8, 2014 6:34 PM
    Moderator
  • Well that is not really what is happening.  With Import-Session you get everything locally and transparent access to remote and local commands.  It is kind of a hybrid session.

    Here I have connected with no import.  The commands are not available:

    PS C:\scripts> .\Connect-O365.ps1
    WARNING: Your connection has been redirected to the following URI:
    "https://pod51042psh.outlook.com/powershell-liveid?PSVersion=4.0 "
    PS C:\scripts> get-mailbox
    get-mailbox : The term 'get-mailbox' is not recognized as the name of a cmdlet, function, script file, or operable
    program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:1
    + get-mailbox
    + ~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (get-mailbox:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    
    PS C:\scripts>

    I can then enter the session but it is a pain becsue I lose all local files:

    PS C:\scripts> get-pssession
    
     Id Name            ComputerName    State         ConfigurationName     Availability
     -- ----            ------------    -----         -----------------     ------------
      1 Session1        pod51042psh.... Opened        Microsoft.Exchange       Available
    
    
    PS C:\scripts> get-pssession|enter-pssession
    [pod51042psh.outlook.com]: PS>get-mailbox
    
    Name                      Alias                ServerName       ProhibitSendQuota
    ----                      -----                ----------       -----------------

    Look what happens if I try to access my local files:

    [pod51042psh.outlook.com]: PS>dir c:
    The term 'dir' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
     of the name, or if a path was included, verify that the path is correct and try again.
    [pod51042psh.outlook.com]: PS>get-childitem c:\
    Command 'get-childitem c:\' was not run as the session in which it was intended to run was either closed or broken
    PS C:\scripts>

    Now I complete the connection by importing the session and I have access to all of my files:

    PS C:\scripts> Import-PSSession $Session
    WARNING: The names of some imported commands from the module 'tmp_ecpdjmit.4rj' include unapproved verbs that might
    make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the
    Verbose parameter. For a list of approved verbs, type Get-Verb.
    
    ModuleType Version    Name                                ExportedCommands
    ---------- -------    ----                                ----------------
    Script     1.0        tmp_ecpdjmit.4rj                    {Add-AvailabilityAddressSpace, Add-DistributionGroupMember...
    
    
    PS C:\scripts> dir
    
    
        Directory: C:\scripts
    
    
    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    d----         7/22/2013   2:20 PM            csvtest
    d----         6/17/2013  11:56 AM            Demo-MFP
    d----         8/10/2013   5:25 PM            EventViewer

    And I have access to the remote commands all at the same prompt.

    S C:\scripts> get-mailbox
    
    ame                      Alias                ServerName       ProhibitSendQuota
    ---                      -----                ----------       -----------------
    paulen                   cpaulen              bl2pr05mb003     49.5 GB (53,150,220,288 bytes)

    Note I am still at the local prompt.


    ¯\_(ツ)_/¯

    Thursday, May 8, 2014 6:50 PM
  • Maybe you right!

    First of all, i not using a remote connection, the commands is processed locally by the server.

    Well think about this way..... what happen when you need to execute a bunch of commands when each of them by his own..

    You have to execute get-exchangeserver balblab record some returned value and then execute get-mailboxdatabase and record but all of this commands is executed on by one, and not in a script or in a active powershell window.

    The environment is a .net agent installed on local server that has list of attributes to monitor, and each attribute have his own command to get his value, so each command have to load exchange snappin and thats the problem.

    So the ideia is to run powershell and load exchange modules, then when each of the commands have to run, powershell connect to that other instance of powershell and run the needed command.

    Something like.....
    When the local agent starts it run..."powershell.exe -add-pssnapin exchange.....; new-psssession"
    When the agent need to run get-exchangeserver it starts "powershell.exe enter-pssession; get-exchangeserver;exit-pssession;exit"

    Doing this, the ideia is that the first powershell will keep running waiting for another command.

    Thats my ideia, but if someone could point me to another direction with the same behavior, thats ok!

    Thanks for help!

    Guilherme Hoescher

    What you are posting makes no sense.   What is a Net agent?  PowerShell is a program.  You run it.  Once running it remembers what you are doing.

    Why Get-ExchangeServer?  Do you have many servers?

    You need to post an example of the script you are trying to run.


    ¯\_(ツ)_/¯

    Thursday, May 8, 2014 6:53 PM
  • Now try:

        Invoke-Command {get-mailbox} -Session (get-pssession 1)

    from your local session.  

    Also note how long it takes to import the session, and what happens to the WS size of the PS process when you do.  If it's for a script that's going to run one command and then exit, why do that if you don't need to?


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "


    Thursday, May 8, 2014 7:10 PM
    Moderator
  • Now try:

        Invoke-Command {get-mailbox} -Session (get-pssession 1)

    from your local session.  


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Yes - but it is noticeable slower. It is reconnecting the session each time. When I import the session it stays connected and is very speedy.


    ¯\_(ツ)_/¯

    Thursday, May 8, 2014 7:14 PM
  • That's why it's good for interactive work.

     In a script that's only going to run one or two Exchange cmdlets and then exit, that's easily offset by not having to spend the time importing the session.  That seems to be the scenario these commands are being run in.


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Thursday, May 8, 2014 7:22 PM
    Moderator
  • Sorry about miss understood ".net agent" but is a program develloped in .net by our team and this agent will stay running on a system like SSCM agent, a antivirus agent etc etc etc and that agent will run commands on local system and send information captured to another server who will monitor any change that happen over the time.

    The command get-exchangeserver is just an example but i have to run a lot of commands that only exist in Exchange PSSnapin to get configuration of entire exchange environment, if exist one or a hundred exchange servers.

    Imagine this cenario for example.
    You have to monitor if someone change de quota settings defined to a mailbox database.
    To do that.....you have to know what is the quota configuration already set.
    To get that information with powershell, you have to load exchange PSSnapin and execute get-mailboxdatabase -server someserver -identity mailboxdatabase | select ProhibitSendReceiveQuota.

    This is one of the monitored attributes, but....if i want to monitor all of exchange attributes one by one i have a lot of commands, that need to be run sometimes during the day.

    Doing this, opening powershell, loading modules, getting values, closing powershell etc etc etc create a big problem...because load exchange pssnapin creates a high server load, this is why i trying to let 1 instance of powershell open with all modules i need and then redirect the commands to that session.

    I hope now its clear enough and many thanks trying to help me.

    Guilherme Hoescher

    Thursday, May 8, 2014 8:13 PM
  • Isn't that what Exchange's Admin Audit logs are for?

    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Thursday, May 8, 2014 8:23 PM
    Moderator
  • The answer is yes!
    But what if you want to create a live documentation of your environment?

    And what if (not in this case because Exchange store information on AD) you lost your server and you need to know how something is configured before the server crash?

    And if you have to control change of servers and work with baseline configuration, setting predefined configurations on a environment....

    I understand your point, but i think we missing the purpose of this thread!! hehe


    Guilherme Hoescher


    Thursday, May 8, 2014 8:32 PM
  • OK, if you're just documenting states, that's a different scenario than what was presented.  

    Everything you're wanting to accomplish can be done through the remote management sessions provided by the Exchange servers, without using the snapin.  Once you are connected to that remote session, you can run the Exchange cmdlets you need either by using Invoke-Command directed at that session, or by importing the session.  

    If you can get past the idea that those commands are only available through the snapin and use the remote sessions you eliminate the problems of the system overhead involved in loading the snapin, along with the maintenance headache of keeping it updated every time a new CU gets applied to the Exchange servers.


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Thursday, May 8, 2014 8:54 PM
    Moderator
  • YOu will likely find that you cannot easily run an exchange shell under a service process.  YOu will also find trhat remoting weven on the same server is the easiest way to access exchange with no issues.  In other words do not rty to use th esnapin.

    If you need to use arbitrary commands over time a C#, VB,Net or other Net program can host PowerShell and open a permanent session.  This wil lbe internal to the service and it can be designed to load and execute arbitrary commands.  This would be the recommended method.  This will eliminate the reloading of PowerShell and Exchaneg and will allow for scripts to be designed and executed when necessary.

    In many ways the task scheduler would be better fo rthis if you are just gather information.

    For tightly couples needs you should really instrument exchange internally .  Exchange has an even model and an API that allow it to be extended.  Thisis how vendors work with Exchange.

    In the end you will have to learn how to use PowerShell and how to solve these design issues. We cannot really be of much help.

    We can answer specific questions.

    This comment makes no sense in the light of all other things you have posted.

    "And what if (not in this case because Exchange store information on AD) you lost your server and you need to know how something is configured before the server crash?"

    I would recommend backing up Active Directory daily.

    You can extract some items from AD but that does not require any of the issues you have posed.  Just write a script and run it.  You can read AD settings without loading the Exchange Shell.

    Exchange also has tools for dumping the configuration that you might want to use.


    ¯\_(ツ)_/¯

    Thursday, May 8, 2014 8:57 PM
  • Hello guys good morning!

    mjolinor i will try you solution keeping our actual cenario where we need to execute arbitrary commands over the time and following our initial concept on how to do that.

    jrv your citations helped me to clarify a new way to see that problem and point me to a different direction on how to do that. This option i will keep in mind and i will try to discuss this with our development team because it is a fact that using Exchange API is the best way to accomplish what we need, and i realy dont even think about it until now. 
    As i think you guys could imagine, i work with infrastructure and i try to help by any means i could, and this is related with the knowledge i have, Powershell and Exchange.

    I really apreciate all time you guys used to help me, thank you.

    Guilherme Hoescher

    Friday, May 9, 2014 12:37 PM
  • Hi guys i find another way to accomplish what i looking for and this is how i do that.

    Create a remote PSSession with Exchange using new-psssession
    Export that Session using export-pssession -session X -commandname get-* -outputmodule Y -allowclobber
    Then when i change the connectionuri inside psm1 file to be a generic name allowing me to use against any server.
    Then when i have to get some configuration on a specific exchange server, i just import that module, specifing the remote server.
    powershell.exe import-module Y;get-anycommandavaileable
    Voila....... using this method i can get any information in something about 1 second with a very low CPU/memory/disk/network consumption and with the old method.... powershell.exe add-pssnapin exchangesnappin; get-anycommandavaileable the time is around 12 seconds with high CPU load!

    Using the concept of remote connection that you mention allow me to run with a very low resource consumption, even when i run the command inside exchange server, because load the module is to much faster then load de pssnapin, and also permit to use the same module in a non exchange server.

    One more time, thank you!


    Guilherme Hoescher

    Friday, May 9, 2014 8:46 PM
  • Yes - you can export the session but different versions of Exchange may have issues with the scripts.  Be careful.  You should probably export from the oldest server version you have installed like only 2007 and sset your session for 2007 compatibility.  This way all commands you choose will always work on all servers.


    ¯\_(ツ)_/¯

    Friday, May 9, 2014 9:07 PM