1

I was under the assumption that PSRunspaces opened using the current PSSession that was active but when I run the script below I get the error message that New/Set-Mailcontact are not recognised commands as if they are running locally. Firstly am I wrong in my thinking? Secondly, if so, is there a way to open the runspace pool in the Office365 PSSession?

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
$TimeStamp = Get-Date -Format g
Import-PSSession $session
Connect-MsolService -cred $UserCredential

$contacts = Import-Csv "C:\temp\testgal.csv"
$RunspaceCollection = @()
[Collections.Arraylist]$ScriptResults = @()
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS+1)
$RunspacePool.Open()

$ScriptBlock = {
    param($c)
    $name = $c.displayName
    $rawProxy = $c.proxyAddresses
    $proxysplit = $rawproxy -split '(?<!\\);'
    $proxyquoted = $proxysplit.replace('x500','"x500').replace('x400','"x400').replace('X500','"X500').replace('X400','"X400')
    $proxy = $proxyquoted
    New-MailContact -ExternalEmailAddress $c.Mail -Name "`"$name`"" -Alias $c.mailNickname -DisplayName $name -FirstName $c.givenName -Initials $c.initials -LastName $c.sn
    Set-MailContact -Identity $c.mailNickname -CustomAttribute1 "CreatedWithScript" -CustomAttribute3 $c.extensionAttribute3 -EmailAddresses $proxy
    Set-Contact -Identity $c.mailNickname -City $c.l -Company $c.company -Department $c.department -Office $c.physicalDeliveryOfficeName -Phone $c.telephoneNumber -PostalCode $c.postalCode -Title $c.title
    return $error[0]
} 

Foreach ($c in $contacts) {
    $Powershell = [PowerShell]::Create().AddScript($ScriptBlock).AddArgument($c)
    $Powershell.RunspacePool = $RunspacePool
    [Collections.Arraylist]$RunspaceCollection += New-Object -TypeName PSObject -Property @{
        Runspace = $PowerShell.BeginInvoke()
        PowerShell = $PowerShell  
    }
}

While($RunspaceCollection) {
    Foreach ($Runspace in $RunspaceCollection.ToArray()) {
        If ($Runspace.Runspace.IsCompleted) {
            [void]$ScriptResults.Add($Runspace.PowerShell.EndInvoke($Runspace.Runspace))
            $Runspace.PowerShell.Dispose()
            $RunspaceCollection.Remove($Runspace)   
        }
    }
}

Write-Host "Results of the scriptlogged to C:\temp\Error_Log.txt..."
$ScriptResults | Out-File 'C:\temp\Error_Log.txt' -Append
A.Gialias
  • 47
  • 2
  • 8
  • I found the following https://stackoverflow.com/questions/31935183/new-pssession-and-runspacepool-clarification could that possibly be rewritten to work in powershell? – A.Gialias Jun 01 '17 at 12:43
  • well, they are not sharing state with your powershell process, so you need to login to o365 in each runspace – 4c74356b41 Jun 01 '17 at 19:03

0 Answers0