Invoke Power Shell: Unable to cast object of type 'System.String' to type 'System.Management.Automation.PSModuleInfo

While running powershell script to manage mail flow in exchange. I am facing this issue ->Invoke Power Shell: Unable to cast object of type ‘System.String’ to type 'System.Management.Automation.PSModuleInfo.
While passing the username and password dynamically this issue occuring. If I hardcoded the credentials means its working fine . But that is not possible in real time, so I have to pass it dynamically from the flow.

@akshayajeyachandran - can you share the screenshot of the flow process…

Here the out argument variable has been returned (Result:not added) and also the mail flow is updated but still this exception is thrown !!

$Username
$Pwd
$Password = ConvertTo-SecureString $Pwd -AsPlainText -Force
$LiveCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
$Getword = Get-TransportRule $Rulename
$Getanswer = $Getword.$Rulecondition
if($Getanswer -clike $Getinput)
{
Set-Variable -Name “desc” -Value “not added”
}
else
{
$Getans = $Getword.$Rulecondition + $Getinput
$value
Set-Variable -Name “desc” -Value “added”
switch($value)
{
1{Set-TransportRule “Subject or body contains ‘spam keywords’” -SubjectOrBodyContainsWords $Getans}
2{Set-TransportRule “Subject or body contains ‘spam keywords’” -ExceptIfFrom $Getans}
}
}
$s = Get-PSSession
Remove-PSSession -Session $s

This is the script

@akshayajeyachandran - can you create a new script file and try to add a simple script and verify the activity…
am suspecting the credentials/microsoft.exchange namespaces…

Same error thrown while using simple script

Script - >

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Confirm:$false
$Username
$Pwd
$Password = ConvertTo-SecureString $Pwd -AsPlainText -Force
$LiveCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://psoutlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Set-TransportRule “Subject or body contains ‘spam keywords’” -SubjectOrBodyContainsWords “testing”
Set-Variable -Name “desc” -Value “added”
Get-PSSession | Remove-PSSession

@akshayajeyachandran - can you change the type to type argument to
System.Management.Automation.PsModuleInfo

I have already kept in that type only in Invoke PowerShell script activity

Hi @akshayajeyachandran ,

Can you change the typeargument as System.String and run the flow.

Thanks,
@Murli_Manohar

Hi @Murli_Manohar

Still having the same issue
image

1 Like