Granfeldt PowerShell MA Import-PSSession?

Firstly
Søren Granfeldt thank you for writing and releasing this MA! I'm using it for Account Expiration dates already!! My issue is when trying to connect to Exchange Online (O365) to manage mailboxes.
I'm using the Granfeldt PowerShell MA to access data in Office 365 but not just the dirsync (is the user licensed) but also properties on the Exchange Online.
I can connect to Exchange Online (O365)  when running the script as the service account (FIMService). It connects using stored credentials to Exchange Online using Remote PowerShell and Importing the session with -AllowClobber. However I get an error
on the Import-PSSession line saying that $Session is undefined / Null when the MA Runs it.
I have a couple of questions.
1) If I edit the import.ps1 script (Import Script) do I need to refresh the PowerShell MA Schema for it to pick up the changes or does it load and run this on the fly?
2) Has any one ran an Import-PSSession with the Granfeldt  PowerShell and gotten a script Error: Script error in line 24: [Cannot validate argument on parameter 'Session'. The argument is null. Supply a non-null argument and try the command again.]
- (At {REMOVED}
+     Import-PSSession -Session $mySession -AllowClobber -WarningAction SilentlyCo ...
The error is under the $mySession variable, it should connect just fine, I've gone so far as hard coding the password into the script.
3) Is there any way to make the import script "Run as Admin / Elevated" ?
Thanks in advance!!!!
Jonathan Manley

I was able to make a test against Exchange Online. The below Import.ps1 works fine in Sorens PS MA.
param (
    $Username,
    $Password
#Create Session
$pw = ConvertTo-SecureString -AsPlainText -Force -String $Password
$O365Credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $Username,$pw
$session = New-PSSession -ConfigurationName "Microsoft.Exchange" -ConnectionUri "https://ps.outlook.com/powershell" -Credential $O365Credentials -Authentication Basic -AllowRedirection
$result = Import-PSSession $session -AllowClobber -CommandName Get-MailUSer
$MailUsers = Get-MailUser
ForEach($MailUser in $MailUsers)
    $obj = @{}
    $obj.Add("Alias",$MailUser.Alias)
    $obj.Add("objectClass", "MailUser")
    $obj
Kent;
Thank you for the script. I created a new import script with just the code here in the post by itself. I still get the following error in the Logs (Turned the logs on using the Registery key per Soren's blog post.)
I'm just including one line above the error and one line below the error. Let me know if more would help.
It's like for some reason the remote PowerShell session doesn't get connected.
4/21/2014 7:48:47 PM: Should impersonate: True
4/21/2014 7:48:50 PM: Script error in line 11: [Cannot validate argument on parameter 'Session'. The argument is null. Supply a non-null argument and try the command again.] - (At C:\Office365-MA\O365Import2.ps1:11 char:28
+ $result = Import-PSSession $session -AllowClobber -CommandName Get-MailUSer
+                            ~~~~~~~~)
4/21/2014 7:48:50 PM: Script error: [ps.outlook.com] Closing remote server shell instance failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
4/21/2014 7:48:50 PM: Page token returned: ''

Similar Messages

  • Import-Pssession is not importing cmdlets when used in a custom module

    I have a PowerShell script/function that works great when I use it in my PowerShell profile or manually copy/paste the function in the PowerShell window.
    I'm trying to make the function accessible to other members of my team as a module. I want to have the module stored in a central place so we can all add it to our PSModulePath.
    Here is a copy of the basic function:
    Function Connect-O365{ $o365cred = Get-Credential [email protected] $session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUrihttps://ps.outlook.com/powershell/ -Credential
    $o365cred -Authentication Basic -AllowRedirection Import-PSSession $session365 -AllowClobber }
    If I save this function in my PowerShell profile it works fine. I can dot source a *.ps1 script with this function in it and it works as well.
    The issue is when I save the function as a *.psm1 PowerShell script module. The function runs fine but none of the exported commands from the Import-PSSession are available. I think this may have something to do with the module scope.
    I'm looking for suggestions on how to get around this.
    I've posted this on www.stackoverflow.com as well but unfortunately haven't had any luck finding a solution.

    Hi,
    As we know there are some kind of powershell profile:
    You can have four different profiles in Windows PowerShell. The profiles are listed in load order. The most specific profiles have precedence over less specific profiles where they apply.
    %windir%\system32\WindowsPowerShell\v1.0\profile.ps1            
    This profile applies to all users and all shells.
    %windir%\system32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1            
    This profile applies to all users, but only to the Microsoft.PowerShell shell.
    %UserProfile%\My Documents\WindowsPowerShell\profile.ps1            
    This profile applies only to the current user, but affects all shells.
    %UserProfile%\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1            
    This profile applies only to the current user and the Microsoft.PowerShell shell.
    What happen when you save it in the first path.
    In addition, please also refer to the below links:
    Windows PowerShell Profiles
    http://msdn.microsoft.com/en-us/library/windows/desktop/bb613488(v=vs.85).aspx
    Understanding the Six PowerShell Profiles
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/05/21/understanding-the-six-powershell-profiles.aspx
    Regards,
    Yan Li
    Cataleya Li
    TechNet Community Support

  • Issue with running powershell script in pssessions

    Hi Everyone,
    I am trying to run powershell script from remote machine using below commands
    C:\Users\user>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    -command "$s= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
    http://Exchservername/PowerShell/ -Authentication Kerberos ; Import-PSsession $s; "C:\Failback.ps1"
    and Below is the failback.ps1.
    $mbxs = Get-MailboxDatabase | Sort Name
    ForEach($mbx in $mbxs)
    $MBdb=$mbx.Name $ServerHosting=$mbx.Server.Name
    if($mbx.activationPreference.value -eq 1)
    If ($ServerHosting -ne $ActivationPreference.Key.Name) 
    Move-ActiveMailboxDatabase $MBdb -ActivateOnServer $ActivationPreference.Key.Name -confirm:$False 
    Below is what i am getting.

    What is your question?  Are you pointing out the yellow text?  This is normal, and appears every time EMS is opened.
    I should also point out that Microsoft provides a script to re-balance databases, if that's what you're trying to accomplish:
    You can use the RedistributeActiveDatabases.ps1 script to balance the active mailbox databases copies across a DAG. This script moves databases between their copies in an attempt to have an equal number of mounted databases on each server in DAG. If required,
    the script also attempts to balance active databases across sites.
    https://technet.microsoft.com/en-us/library/dd335158(v=exchg.141).aspx
    Mike Crowley | MVP
    My Blog --
    Baseline Technologies

  • Søren Granfeldt PowerShell MA Export

    Hello everyone!
    I have the following strange behavior with Søren Granfeldt PowerShell MA on Export:
    I am using CSEntryChange objects on Export, so i want to determine only changed values in multivalue attributes.
    Here is the example of export:
    To display changed values in debug file i am using following powershell code:
        $atrChng = $_.ChangedAttributeNames
        foreach ($can in $atrChng)
            "Name: $can" | Out-File $DebugFile -Append
            foreach ($ValueChange in $_.AttributeChanges[$can].ValueChanges)
                 $val = $ValueChange.Value
                 $valmodt = $ValueChange.ModificationType
                 "Value: $val $valmodt " | Out-File $DebugFile -Append
    In my debug file i have the following result:
    Name: members
    Value: u6000041 Add 
    Value: u6000042 Add 
    Value: u6000048 Add 
    This means that all attributes, even those that not have been changed are display as added attributes.
    I have an idea that this behavior is because of Object Replacement type export of this MA. If i am right, does this mean, that there are no ways for me to get only changed values instead of sort out all of them? In my case i should exactly know
    changed values to execute the target system API functions AddUserToGroup() or DeleteUserFromGroup() for each.
    The other option is that i am doing something wrong :)
    Thanks in advance for any help!

    It is configured to do object replacement currently. However, if you - as it looks like you done - deselect the "Export Simple Objects" on the MA, you should be able to get the the AttributeChanges property on the exported CSEntryChange object
    - and go from there using the MSDN documentation for this type of object (http://msdn.microsoft.com/en-us/library/microsoft.metadirectoryservices.csentrychange(v=vs.100).aspx).
    Remeber that the AttributeChanges consists of a list objects of type AttributeChange, which again have some properties (i.e. ValueChanges) that you may want to examine (http://msdn.microsoft.com/en-us/library/microsoft.metadirectoryservices.attributechange_properties(v=vs.100).aspx)
    You have to dig deeeeep...deeper that what you're doing with your current script. I have yet to go there...
    Regards, Soren Granfeldt
    blog is at http://blog.goverco.com | facebook https://www.facebook.com/TheIdentityManagementExplorer | twitter at https://twitter.com/#!/MrGranfeldt

  • How do I suppress messages/loading bars from Import-Module and Import-PSSession?

    Hello,
    How do I suppress messages/loading bars from Import-Module and Import-PSSession?
    I am writing a script that will be using these commands and it makes the script look clunky/scary to novice users.
    Thank you for your time.

    Sorry to bring this back up, but it seems that the ProgressPreference worked for Exchange, but it didn't affect the Active Directory progress bar. Any ideas why?
    Strange, this worked just fine for me (no module loading indication):
    PS C:\Users\mike.admin> $ProgressPreference = 'SilentlyContinue'
    PS C:\Users\mike.admin> Get-ADUser mike.admin | Select Name
    Name
    mike.admin
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)
    I do run the Import-Module command inside a function, but I doubt that would do it because I assume the preference is set scriptwide.
    This will work anywhere.
    $global:ProgressPreference='SilentlyContinue'
    ¯\_(ツ)_/¯

  • How to import multi-value reference with Granfeldt PowerShell MA?

    Hi,
    I am trying to import multi-value reference into FIM (Group object).
    I can import all attributes from source SQL, except Multivalue reference (into members attribute on Group object).
    I have defined schema like this:
    $obj = New-Object -Type PSCustomObject
    $obj | Add-Member -Type NoteProperty -Name "Anchor-axs_profid|String" -Value ""
    $obj | Add-Member -Type NoteProperty -Name "objectClass|String" -Value "role"
    $obj | Add-Member -Type NoteProperty -Name "name|String" -Value ""
    $obj | Add-Member -Type NoteProperty -Name "member|Reference[]" -Value ""
    $obj
    On source attribute I have members defined in one attribute, divided by ",". 
    Import script:
    $Obj = @{}
    $Obj.Add("objectClass", "role")
    $Obj.Add("[DN]", "Role_"+$Object.$("axs_profid"))
    $Obj.Add("axs_profid", $Object.$("axs_profid").ToString())
    $Obj.Add("name", $Object.$("name").ToString())
    if($Object.$("member").ToString() -ne "")
    [string[]]$members = $Object.$("member").ToString().Split(',')
    $Obj.Add("member", $members)
    $Obj
    When Full import is triggered, I get following error for roles with multiple users:
    FIM Sync = staging-error
    Event log = 
    The server encountered an unexpected error in the synchronization engine:
     "BAIL: MMS(9588): d:\bt\32669\private\source\miis\shared\utils\libutils.cpp(7045): 0x8023040e (The distinguished name is invalid)
    BAIL: MMS(9588): d:\bt\32669\private\source\miis\server\sqlstore\utils.cpp(229): 0x8023040e (The distinguished name is invalid)
    BAIL: MMS(9588): d:\bt\32669\private\source\miis\server\sqlstore\nscsimp.cpp(5348): 0x8023040e (The distinguished name is invalid)
    BAIL: MMS(9588): d:\bt\32669\private\source\miis\server\sqlstore\nscsimp.cpp(5753): 0x8023040e (The distinguished name is invalid)
    BAIL: MMS(9588): d:\bt\32669\private\source\miis\server\sqlstore\nscsimp.cpp(686): 0x8023040e (The distinguished name is invalid)
    BAIL: MMS(9588): d:\bt\32669\private\source\miis\server\sqlstore\csobj.cpp(12876): 0x8023040e (The distinguished name is invalid)
    BAIL: MMS(9588): d:\bt\32669\private\source\miis\server\sqlstore\csobj.cpp(13976): 0x8023040e (The distinguished name is invalid)
    BAIL: MMS(9588): d:\bt\32669\private\source\miis\server\sqlstore\csobj.h(1252): 0x8023040e (The distinguished name is invalid)
    ERR_: MMS(9588): d:\bt\32669\private\source\miis\server\sync\syncstage.cpp(2018): ERR_: MMS(9588): d:\bt\32669\private\source\miis\server\sync\syncstage.cpp(612): ERR_: MMS(9588): d:\bt\32669\private\source\miis\server\sync\syncstage.cpp(647): Staging failed
    0x8023040e: [21]ERR_: MMS(9588): d:\bt\32669\private\source\miis\server\sync\syncmonitor.cpp(2528): SE: Rollback SQL transaction for: 0x8023040e
    Forefront Identity Manager 4.1.3559.0"
    If I change the script to return only first member:
    $Obj.Add("member", $members[0])
    import is successfull and I can see referenced member in Group.
    I have also tried to specify DN for both users and roles with the same outcome.
    $Obj.Add("[DN]", "Role_"+$Object.$("axs_profid"))
    I am using the latest version of  PSMA: 5.5
    Thanks for your help guys!

    I managed to solve this issue.
    The problem was in string array (I always appended "," at the end of each value). MA then expected another value after the last comma.
    The wrong approach:
    [string[]]$members = $Object.$("member").ToString().Split(',')
    The right approach:
    [string[]]$members = $Object.$("member").ToString().TrimEnd(',').Split(',')

  • Using PowerShell to import CSV data from Vendor database to manipulate Active Directory Users

    Hello,
    I have a big project I am trying to automate.  I am working in a K-12 public education IT Dept. and have been tasked with importing data that has been exported from a vendor database via .csv file into Active Directory to manage student accounts. 
    My client wants to use this data to make bulk changes  to student user accounts in AD such as moving accounts from one OU to another, modifying account attributes based on State ID, lunchroom ID, School, Grade, etc. and adding new accounts / disabling
    accounts for students no longer enrolled.
    The .csv that is exported doesn't have headers that match up with what is needed for importing in AD, so those have to be modified in this process, or set as variables to get the correct info into the correct attributes in AD or else this whole project is
    a bust.  He is tired of manually manipulating the .csv data and trying to get it onto AD with few or no errors, hence the reason it has been passed off to me.
    Since this information changes practically daily, I need a way to automate user management by accomplishing the following on a scheduled basis.
    Process must:
    Check to see if Student Number already exists
    If yes, then modify account
    Update {School Name}, {Site Code}, {School Number}, {Grade Level} (Variables)
    Add correct group memberships (School / Grade Specific)
    Move account to correct OU (OU={Grade},OU=Students,OU=Users,OU={SiteCode},DC=Domain,DC=net)
    Remove incorrect group memberships (School / Grade Specific)
    Set account status (enabled / disabled)
    If no, create account
    Import Student #
    Import CNP #
    Import Student name
    Extract First and Middle initial
    If duplicate name exists
    Create log entry for review
    Import School, School Number, Grade Level
    Add to correct Group memberships (School / Grade Specific)
    Set correct OU (OU={Grade},OU=Students,OU=Users,OU={SiteCode},DC=Domain,DC=net)
    Set account Status
    I am not familiar with Powershell, but have researched enough to know that it will be the best option for this project.  I have seen some partial solutions in VB, but I am more of an infrastructure person instead of scripting / software development. 
    I have just started creating a script and already have hit a snag.  Maybe one of you could help.
    #Connect to Active Directory
    Import-Module ActiveDirectory
    # Import iNOW user information
    $Users = import-csv C:\ADUpdate\INOW_export.csv
    #Check to see if the account already exists in AD
    ForEach ( $user in $users )
    #Assign the content to variables
    $Attr_employeeID = $users."Student Number"
    $Attr_givenName = $users."First Name"
    $Attr_middleName = $users."Middle Name"
    $Attr_sn = $users."Last Name"
    $Attr_postaldeliveryOfficeName = $users.School
    $Attr_company = $users."School Number"
    $Attr_department = $users."Grade Level"
    $Attr_cn = $Attr_givenName.Substring(0,1) + $Attr_middleName.Substring(0,1) + $Attr_sn
    IF (Get-ADUser $Attr_cn)
    {Write-Host $Attr_cn already exists in Active Directory

    Thank you for helping me with that before it became an issue later on, however, even when modified to be $Attr_sAMAaccountName i still get errors.
    #Connect to Active Directory
    Import-Module ActiveDirectory
    # Import iNOW user information
    $Users = import-csv D:\ADUpdate\Data\INOW_export.csv
    #Check to see if the account already exists in AD
    ForEach ( $user in $users )
    #Assign the content to variables
    $Attr_employeeID = $users."Student Number"
    $Attr_givenName = $users."First Name"
    $Attr_middleName = $users."Middle Name"
    $Attr_sn = $users."Last Name"
    $Attr_postaldeliveryOfficeName = $users.School
    $Attr_company = $users."School Number"
    $Attr_department = $users."Grade Level"
    $Attr_sAMAccountName = $Attr_givenName.Substring(0,1) + $Attr_middleName.Substring(0,1) + $Attr_sn
    IF (Get-ADUser $Attr_sAMAccountName)
    {Write-Host $Attr_sAMAccountName already exists in Active Directory
    PS C:\Windows\system32> D:\ADUpdate\Scripts\INOW-AD.ps1
    Get-ADUser : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADUser'
    required by parameter 'Identity'. Specified method is not supported.
    At D:\ADUpdate\Scripts\INOW-AD.ps1:28 char:28
    + IF (Get-ADUser $Attr_sAMAccountName)
    + ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.GetAD
    User

  • Powershell generic session and import this session in Exchange remote management session c#

    The situation :
    I am trying to make an application (c#-asp.net) to manipulate user's on an exchange server. The application will be on a different server than the exchange's one. So, to manipulate the data, I am using an "Exchange remote management session" created
    with c#. Exchange remote management session give access to simple powershell command like "New-Mailbox" and "Set-User" - This is good for simple task, but in my case, I have to do more complexe operations that will need some specific command
    that is not included in the default command. To access this command, I have to use some specific module like "ActiveDirectory". It is simple ? Only use "Import-Module" ! Not really, like I said, the "Exchange remote management session"
    is very limited with the command, and "Import-Module" is not allowed...
    So what we can do ?
    I read a lot about my problem, and the most "simple" (That I understand the theory) solution is something like :
    Start with a generic PS session, import the AD module, then connect to an Exchange management session and do an Import-PSSession and use implicit remoting for the
    Exchange management stuff.
    Given that I am pretty new to manipulate the Powershell with c#, I have no idea how to use this awesome solution in my code. So I am asking your help.
    Here's my current code :
    // Prepare the credentials.
    string runasUsername = @"MarioKart 8";
    string runasPassword = "MarioKart";
    SecureString ssRunasPassword = new SecureString();
    foreach (char x in runasPassword)
    ssRunasPassword.AppendChar(x);
    PSCredential credentials =
    new PSCredential(runasUsername, ssRunasPassword);
    // Prepare the connection
    var connInfo = new WSManConnectionInfo(
    new Uri("MarioKart8Server"),
    "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
    credentials);
    connInfo.AuthenticationMechanism =
    AuthenticationMechanism.Basic;
    connInfo.SkipCACheck = true;
    connInfo.SkipCNCheck = true;
    // Create the runspace where the command will be executed
    var runspace = RunspaceFactory.CreateRunspace(connInfo);
    // create the PowerShell command
    var command = new Command("New-Mailbox");
    // Add the command to the runspace's pipeline
    runspace.Open();
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);
    // Execute the command
    var results = pipeline.Invoke();
    if (results.Count > 0)
    System.Diagnostics.Debug.WriteLine("SUCCESS");
    else
    System.Diagnostics.Debug.WriteLine("FAIL");
    This code work great for simple task (like "New-Mailbox") ! But how can I create a "generic PS session" and then use this session in the "Exchange remote management session" ?

    Hi Vincent,
    Generally we can use the cmdlet "import-module" to import the AD module on DC (Domain Controller), and we can also create a exchange remote powershell session with the cmdlet new-pssession, for more detailed information to create exchange remote session,
    please refer to this article:
    Managing Exchange 2010 with Remote PowerShell
    In addition, to invoke powershell cmdlet in C#, please also try to save all the cmdlets to a powershell script (.ps1 file), then we can add the powershell script to C# like:
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);
    If I have any misunderstanding, please let me know.
    Best Regards,
    Anna Wang

  • Exchange Powershell return value from Get-command to variable.

    Hi
    I am trying to create a powershell-script for our monitoring-software.
    The script is supposed to establish a connection to our exchange-server mgmt-shell and execute this command:
    "Get-MailboxDatabaseCopyStatus"
    I have the connection in place, but am missing the knowledge of how to return the result of the command to my script, which I can then pass to our monitoring-software.
    (The script take 2 parameters - host and command eg. exch01.domain and Get-MailboxDatabaseCopyStatus).
    Current code:
    $statusAlive = "ScriptRes:Host is alive:"
    $statusDead = "ScriptRes:No answer:"
    $statusUnknown = "ScriptRes:Unknown:"
    $statusNotResolved = "ScriptRes:Unknown host:"
    $statusOk = "ScriptRes:Ok:"
    $statusBad = "ScriptRes:Bad:"
    $statusBadContents = "ScriptRes:Bad contents:"
    $pass = cat C:\securestring.txt | convertto-securestring
    $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "domain\administrator",$pass
    $host = $args[0]
    $command = $args[1]
    <#
    if (!$args[0]) {
    echo $statusUnknown"Host parameter is empty"
    exit
    if (!$args[1]) {
    echo $statusUnknown"Command parameter is empty"
    exit
    #>
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$host/powershell -Credential $cred
    Import-PSSession $session
    $command
    Remove-PSSession $session
    Now, how do I "catch" the value of the executed command and return it to a variable in the script?
    Best Regards,
    Soren

    Hmm.. doesnt seem to work quite right.
    I added "Echo $result" after "Remove-PSSession $session", but then I just get a bunch of information..
    Script tmp_c3a1c132-f4d9-4d61... {Get-IRMConfiguration, New-MailUser, Get-PublicFolderMigrationRequestSta...
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB02 - Specielle\EXCHANGE01
    Id : DB02 - Specielle\EXCHANGE01
    Name : DB02 - Specielle\EXCHANGE01
    DatabaseName : DB02 - Specielle
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8124
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 0
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    RunspaceId : 2d179364-2df3-483d-a192-f5f4ca9453bb
    Identity : DB01 - Standard\EXCHANGE01
    Id : DB01 - Standard\EXCHANGE01
    Name : DB01 - Standard\EXCHANGE01
    DatabaseName : DB01 - Standard
    Status : Mounted
    InstanceStartTime : 01-03-2014 03:35:07
    LastStatusTransitionTime :
    MailboxServer : EXCHANGE01
    ActiveDatabaseCopy : EXCHANGE01
    ActiveCopy : True
    ActivationPreference : 1
    StatusRetrievedTime : 11-03-2014 08:30:15
    WorkerProcessId : 8140
    ActivationSuspended : False
    ActionInitiator : Unknown
    ErrorMessage :
    ErrorEventId :
    ExtendedErrorInfo :
    SuspendComment :
    RequiredLogsPresent :
    SinglePageRestore : 0
    ContentIndexState : Healthy
    ContentIndexErrorMessage :
    ContentIndexVersion : 1
    ContentIndexBacklog : 3
    ContentIndexRetryQueueSize : 0
    ContentIndexMailboxesToCrawl :
    ContentIndexSeedingPercent :
    ContentIndexSeedingSource :
    CopyQueueLength : 0
    ReplayQueueLength : 0
    ReplaySuspended : False
    ResumeBlocked : False
    ReseedBlocked : False
    MinimumSupportedDatabaseSchemaVersion : 0.121
    MaximumSupportedDatabaseSchemaVersion : 0.125
    RequestedDatabaseSchemaVersion : 0.125
    LatestAvailableLogTime :
    LastCopyNotificationedLogTime :
    LastCopiedLogTime :
    LastInspectedLogTime :
    LastReplayedLogTime :
    LastLogGenerated : 0
    LastLogCopyNotified : 0
    LastLogCopied : 0
    LastLogInspected : 0
    LastLogReplayed : 0
    LowestLogPresent : 0
    LastLogInfoIsStale : False
    LastLogInfoFromCopierTime :
    LastLogInfoFromClusterTime :
    LastLogInfoFromClusterGen : 0
    LogsReplayedSinceInstanceStart : 0
    LogsCopiedSinceInstanceStart : 0
    LatestFullBackupTime :
    LatestIncrementalBackupTime :
    LatestDifferentialBackupTime :
    LatestCopyBackupTime :
    SnapshotBackup :
    SnapshotLatestFullBackup :
    SnapshotLatestIncrementalBackup :
    SnapshotLatestDifferentialBackup :
    SnapshotLatestCopyBackup :
    LogReplayQueueIncreasing : False
    LogCopyQueueIncreasing : False
    ReplayLagStatus :
    DatabaseSeedStatus :
    OutstandingDumpsterRequests : {}
    OutgoingConnections :
    IncomingLogCopyingNetwork :
    SeedingNetwork :
    DiskFreeSpacePercent : 50
    DiskFreeSpace : 20.02 GB (21,498,761,216 bytes)
    DiskTotalSpace : 40 GB (42,946,523,136 bytes)
    ExchangeVolumeMountPoint :
    DatabaseVolumeMountPoint : E:\
    DatabaseVolumeName : \\?\Volume{e6cb407f-e4f2-11e2-93eb-005056ae239d}\
    DatabasePathIsOnMountedFolder : False
    LogVolumeMountPoint : F:\
    LogVolumeName : \\?\Volume{e6cb4087-e4f2-11e2-93eb-005056ae239d}\
    LogPathIsOnMountedFolder : False
    LastDatabaseVolumeName :
    LastDatabaseVolumeNameTransitionTime :
    VolumeInfoError :
    IsValid : True
    ObjectState : Unchanged
    I am only interested in the 2 "ContentIndexState" - how can I pick these 2 out and put them into a variable?
    I though the command "Get-MailboxDatabaseCopyStatus" would only display these two, since it is what happens if I run the command inside PowerShell on the server itself.

  • Exchange PowerShell script to get mailbox properties of user from a CSV file

    Hi Team,
    I've a CSV file with alias of numerous users and I want to get their mailbox sizes and other properties. These users are dispersed in various databases of same Exchange organization.
    Need a Powershell Script, Any help?
    Muhammad Nadeem Ahmed Sr System Support Engineer Premier Systems (Pvt) Ltd T. +9221-2429051 Ext-226 F. +9221-2428777 M. +92300-8262627 Web. www.premier.com.pk

    You can use this and modify it to what you need. Output to a file (IE: Export-CSV "path to file"
    If you need more specifics let me know. This one is for one user at a time but can be used to read a CSV file.
    # Notifies the user a remote session needs to be started
    Write-Host "Get a users mailbox size" -fore yellow -back red;
    Write-Host "Please wait while a remote session started" -fore red -back yellow;
    # Import a remote session with exchange
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeservername/Powershell/ -Authentication Kerberos
    Import-PSSession $Session
    Do {
    # Prompts user for a name
    $name = Read-Host "Enter a username"
    # Get the mailbox statistics for that user
    Get-MailboxStatistics $name | fl totalitemsize, storagelimitstatus, totaldeleteditemsize | out-default
    # Give the user a choice to test another or EXIT
    $Output = Read-Host "Press Y to continue or ENTER to exit"
    # Ends the program if the user does not press Y
    Until ($Output -ne "Y")
    HossFly, Exchange Administrator

  • Powershell 4 on windows 8.1

    Last summer I had a fun time trying to figure out how to use powershell to import users into Office 365.  After weeks of grief I got my scripts to work and imported 1200 users into a new O356 environment.  It was debatable whether it was quicker
    than doing it long hand, but I figured that next year (as in NOW) the time spent would be worth it.  Wrong!
    So here I am now running on Windows 8.1 pro and I'm back at the start. 
    Import-Module MSOnline is not recognised but this time the Microsoft online service modules seem to be installed.  Nothing works and all my PowerShell books and O365 books are out of date after £100's!
    Here's what I get and I've tried all I know and failed.  I've only got three days to get it done but I've only got 200 users.  Its a race! Lets see if PowerShell can waste more of my time than doing it long hand.  Will anyone come to PowerShell's
    rescue?
    PS C:\WINDOWS\system32> $LiveCred = Get-Credential
    $Session = New-PSSession -ConfigurationName Microsoft. Exchange -ConnectionUri
    https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
    Import-PSSession $Session
    cmdlet Get-Credential at command pipeline position 1
    Supply values for the following parameters:
    New-PSSession : A positional parameter cannot be found that accepts argument 'Exchange'.
    At line:2 char:12
    + $Session = New-PSSession -ConfigurationName Microsoft. Exchange -ConnectionUri h ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [New-PSSession], ParameterBindingException
        + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewPSSessionCommand
    Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for
    the argument, and then try running the command again.
    At line:3 char:18
    + Import-PSSession $Session
    +                  ~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [Import-PSSession], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSessionCommand
    PS C:\WINDOWS\system32> Import-Module MSOnline
    Import-Module : The specified module 'MSOnline' was not loaded because no valid module file was found in any module
    directory.
    At line:1 char:1
    + Import-Module MSOnline
    + ~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ResourceUnavailable: (MSOnline:String) [Import-Module], FileNotFoundException
        + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
    PS C:\WINDOWS\system32>

    Start like this:
    Try{
    $LiveCred=Get-Credential [email protected] -ea stop
    $session=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection -ea Stop
    Import-PSSession $session
    Catch{
    Write-Host "$_" -ForegroundColor red
    pause
    exit
    Write-Host 'Connected and loaded!' -ForegroundColor green
    ¯\_(ツ)_/¯

  • How to create Contacts in PowerShell

    Setup:
    Windows Server 2012 R2 Domain Controllers
    Windows Server 2012 Domain Functional Level
    Windows Server 2012 R2 ADFS with Office 365
    Exchange Online (Not On-Prem)
    I created a csv file that holds Name, FirstName, LastName, ExternalEmailAddress for a list of users I need to import into AD via PowerShell. I tried using the Azure PowerShell to create the contacts in O365>Exchange Online but that has failed because
    of our ADFS with O365.
    Is there a way to run this in PowerShell to create the Contacts in Active Directory? I do not have Exchange On-Prem anymore so I cannot use New-MailContact cmdlet locally. Once again that did not work with Exchange Online PowerShell. I received an error
    stating it already exists for most of the users in the csv file even though I do not have them created as a contact in my AD but there are User accounts. Not the same thing so not sure why O365 gave me an error.
    Any help/Guidance is appreciated. Thanks!

    Hi Blacksuit,
    If you want to create contact in Office 365, how about using Exchange online remotely, you can create a remote powershell session to connect Exchange online:
    $LiveCred = Get-Credential
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell/" -Credential $LiveCred -Authentication Basic -AllowRedirection
    Import-PSSession $Session
    The result is for your reference:
    If there is anything else regarding this issue, please feel free to post back.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

  • How can I Deny permissions to logon to Remote Desktop Session Host server in powershell script?

    I am need of some assistance please. I am a system admin and I am trying to create a script that will assist with the tedious tasks I have to do with disabling a user that no longer works for the company.
    I have created a script so far that will reset the users passwords and remove them from all groups (minus domain users).
    I am trying to make it where it will deny permissions to logon to Remote Desktop Session Host server as well as give full mailbox permission to the manager in Exchange Server 2010.
    I know with Exchange 2010, I will need to add the Powershell snapin. Is there a way for this to be added into the script? I am thinking to add the code:
    add-pssnapin Microsoft.exchange.management.powershell.e2010
    Is there another way to do this? Any help or recommendations would be much appreciated.
    $ou = Get-ADUser -SearchBase "<*OU info here*>" -Filter * |
    Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "<*Password here*>" -Force)
    foreach ($user in $ou) {
    $UserDN = $user.DistinguishedName
    Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
    if ($_.name -ne "Domain Users") {remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False} }

    Why not just disable the account?Why are you searching an OU foro users when you just want to terminate one user?
    You can remotely connect an exchange session and manipulate the mailbox permissions.  You do not load a snap-in except on the Exchange server.
    $Session=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<FQDN of Exchange 2013 Client Access server>/PowerShell/
    Import-PSSession $Session
    # exchange commands here
    \_(ツ)_/
    We have a checklist we have to go through with the tasks listed. We have to keep to the account enabled until HR changes
    the status which is usually 30-90 days depending. Managers sometimes need to access the accounts to retrieve information, etc. We put the users in an OU; once we are given permission from the manager we move forward in the removal. 

  • Using the "Run Powershell command" in Task Sequence

    Hi,
    We are having problems executing PowerShell Scripts from within a TaskSequence. We use this to perform different actions on our servers.
    * We have a GPO for Windows PowerShell that is set to "allow all scripts"
    * In Sccm, the computer agent setting is set to "bypass"
    *In the deployement we specify that we want to run the content from the DP
    When we run the TaskSequence, powershell is started but the script is not executed. The TS is stuck at this time and is just waiting for the script to execute... After killing the powershell process, the TS failes (of course).
    How can we get this working:
    -by disabling the GPO -> indeed then it works
    -by downloading the content locally (we don't want that either)
    Is there any other solution to this?
    I've also tried this but no go:
    Quote:
    Please note, that this policy will only work for scripts which are executed locally. If you want to execute ps1 scripts from a network drive it might be neccessary to add the dp server name into the trusted sites of the IE!
    Source:http://social.technet.microsoft.com/Forums/en-US/a2d44774-a352-40f6-93be-037ccf0bc98b/not-able-to-execute-powershell-scripts-when-running-a-task-sequence-or-running-from-packageprogram?forum=configmanagersdk
    I also tried to run it via the command line option and call powershell.exe, same problem. Executing a scriptblock on the other hand does work. (In the scriptblock, it put get-executionpolicy and it is returning unrestricted)
    Thanks,
    WiM
    IC3CUB3

    Add below to .ps1 file
    $session = New-pssession
    Import-PSSession $session
    New-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\AutoRotation' -Name Enable -Value  0 -PropertyType Dword" 
    Schedule task
    ================
    Program to choose
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    add argument section 
    powershell.exe -noprofile -executionpolicy bypass -file \\server\file.ps1

  • How do I get the new 2013 powershell snap-in

    Is there a way to install just the powershell snap-in for exchange 2013. My group does end user support and needs the tools to create accounts and run our powershell scripts . we don't manage or maintain the server itself.
    In the past we would get the exchange download and during install choose only the management tools which would install the snap-in along with the EMC.
    I understand that the EMC is gone but i still need the snap in and the server install doesn't appear to be readily available for download. I was directed to
    http://www.microsoft.com/en-us/download/details.aspx?id=44022
    which I tried to install there was no option for only the management tools, Someone suggested trying an unattended install with the /roles:t option but that hit a lot of prerequisite problems including trying to update the domain itself.
    All I need is the snap-in is there something I can use to install only that?

    HI AD-Tester,
    For managing and creating account you will need to create and grant admin/management roles to your group:
    http://technet.microsoft.com/en-us/library/dd298183(v=exchg.150).aspx
    Your group then log in to ECP (replacement for Management Console).Logging in to ECP doesnt require anything to be installed,just Internet Explorer or other browsers.
    (Normally ECP link is: https://server.domain.local/ecp )
    For running Exchange powershell,you can use windows powershell ISE then run this:
    $secpasswd = ConvertTo-SecureString "EnterHighlySecurePasswordHere!!!!" -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential ("adm_yourusername", $secpasswd)
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeserver.domain.local/PowerShell/ -Authentication Kerberos -Credential $mycreds
    Import-PSSession $Session
    You can either run this directly or open notepad,paste in the code and save it as .ps1 file.
    Then run this file in Windows Powershell ISE.
    You will now be able to execute exchange powershell commands.
    I use this regularly and havent failed so far :)
    Please mark as helpful if you find my contribution useful or as an answer if it does answer your question. That will encourage me - and others - to take time out to help you. Thank you! Off2work

Maybe you are looking for

  • Mappings not triggered from Process flow?

    Hi, I have some mappings under a process flow..they are triggered daily but today they were not triggered can anyone tell me how to go about this?

  • How do I get my phone to vibrate without a ringtone?

    I would like for my phone to vibrate only when I receive a new email or text message, but still ring when I get a phone call.  Please tell me there's a way to do this!  I've looked everywhere on my phone settings and it just doesn't seem to work.  Do

  • MEPo000

    Hey everyone, I am getting an error message while creating a Purchase Order which says " Purchase order still contains faulty items''  with error message no MEPo000. But there is no further information. Also I am getting an error message which says '

  • Boolean text property in array of booleans

    I am having difficutly in creating a simple program that creates an array of clusters of boolean controls where each boolean has its own custom text.  I attempt to auto create the boolean text in a loop and then after writing to change each individua

  • How to use css masks in firefox?

    masks not working in firefox