Cant cast object of type in powershell

Hi, I’m currently using a powershell script to get a quarantined message from Office 365 by looking searching with a string called messageId. My code works up until

Get-QuarantineMessage -MessageId $MessageID
The error I get is below

I’m unable to cast object of type
‘System.Management.Automation.PsCustomObject’ to type ‘System.Management.Automation.PsModuleInfo’

This is my script below

param(
[string]$MessageId)

$password = ConvertTo-SecureString 'password' -AsPlainText -Force  

$UserCredential = New-Object System.Management.Automation.PSCredential ('user@user.com', $password)


$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/powershell-liveid/' -Credential $UserCredential -Authentication Basic -AllowRedirection

Import-PSSession $Session

Get-QuarantineMessage -MessageId "<d7b90ba6-14bb-4050-9cf8-ffd7de2f3eec@CO1GMEHUB11.gme.gbl>"

Hi @michael.p.wilson,
Have you tried if the same is happening with use Get-Credential instead of New-Object System.Management.Automation.PSCredential?

I Dont think Get-Credential works because the cmdlet cant load up the prompt to enter the details.

You are working with this script in Studio or only in PowerShell at the moment? If second option then cmd will normally popup for the credentials.

Working in studio.

Is your script normally working in PowerShell only?

Yes thats correct.

I ran the code line by line in studio and I only get the error on

Get-QuarantineMessage -MessageId "<d7b90ba6-14bb-4050-9cf8-ffd7de2f3eec@CO1GMEHUB11.gme.gbl>"

Not sure if it helps but try to invoke script this way:

Same Error.

In the ‘Misc’ section what "TypeArgument’ should i be using?

Based on your error seems that it should be set to System.Management.Automation.PsModuleInfo but sometimes it’s tricky. Sometimes whole scripts are using different arguments and you need to divide script for a separate invoked blocks where one block will trigger another one using it’s output.

1 Like