0

I have Python code that is supposed to use Powershell to connect to an exchange server and remove messages from the Queue. (I am new to Powershell)

I have found this which also led to this. Which basically says I should do:

Remove-Message -Server SERVERNAME -Filter {FromAddress -like '*MATCH*'} -WithNDR $false

Where SERVERNAME and MATCH will be given by the code... My problem was how should I run this in the Powershell? So I did this:

powershell -NoExit -Command "COMMAND"

Where COMMAND is the command above. And I want to run that with subprocess. When I test the command manually I get this error:

The term 'Remove-Message' 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:15
+ Remove-Message <<<< -Server SERVERNAME -Filter {FromAddress -like '*MATCH*'} -WithNDR $false
    + CategoryInfo : ObjectNotFound: (Remove-Message:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

So I figure I am doing something wrong, though I think I am passing the arguments correctly into Powershell.

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131

1 Answers1

0

I didn't try using the remove-message cmdlet. Assume the command you provide could work as you expected. You should do following things,

1) Write a script to contain commands including connect to exchange, and remove message

    if ((gcm Remove-Message -ErrorAction Ignore) -eq $null)
    {
      $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$($env:COMPUTERNAME).$($env:USERDNSDOMAIN)/Powershell?serializationLevel=Full;ExchClientVer=14.2.247.5" -Authentication kerberos
      Import-Module (Import-PSSession $session) -global
    }
    Remove-Message -Server SERVERNAME -Filter {FromAddress -like '*MATCH*'} -WithNDR $false

Please make proper change to the -ConnectionUri as I just shows how to connect to local with fully qualified domain name.

2) invoking this script with following code, don't use -NoExit, unless you wan't to continue use that powershell console when the removing finished.

powershell -command ". 'PS_FILE_PATH'"

3) if you need to pass parameters into the script, you could combine them into the -command ". 'script.ps1' arg1 arg2". and use them in the script with $args[0], or declare param first with param($match,$servername) then use in the script.

I'm not so familiar with Python, so I can't provide more info about how to invoke with python.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Jackie
  • 2,476
  • 17
  • 20