如何从Powershell中的Servicebus消息获取消息正文?

时间:2019-03-26 15:16:49

标签: azure powershell .net-core azureservicebus

我试图了解一些PowerShell和dotnet,所以我在使用发现的代码。

我正在尝试使用PowerShell从服务总线中提取一些消息,并且能够发送到队列,但是接收消息时我有些失落。

我可以获取消息的ID,但无法获取正文。

我在帖子中附带的代码给了我以下异常。

  

”以“ 2”作为参数调用“ Invoke”:“期望元素'string'   来自命名空间'http://schemas.microsoft.com/2003/10/Serialization/'..   遇到名称为'FileInfo'的'Element',名称空间   'http://schemas.datacontract.org/2004 /07/System.IO'。 “

如果必须使用PowerShell,这是执行此操作的正确方法吗?

我已经研究了datacontractserializer的Microsoft文档(我认为是这样吗?),但是我不确定将其从dotnet转换为PowerShell的格式

$BindingFlags= [Reflection.BindingFlags] "Public,Instance"
$generic_method = $message.GetType().GetMethod("GetBody",$BindingFlags,$null, @(),$null).MakeGenericMethod([String]).Invoke($message,$null)

1 个答案:

答案 0 :(得分:0)

下载并尝试此示例以学习…

biz.dfch.PS.Azure.ServiceBus.Client 1.0.2.20160609

function Get-MessageBody {
<# 
.SYNOPSIS 
Get the message body from a Service Bus Message. 

.DESCRIPTION 
Get the message body from a Service Bus Message. 

.OUTPUTS 
This Cmdlet returns the Body as [String] from the MessageFactory Message object. On failure it returns $null. 

.INPUTS 
See PARAMETER section for a description of input parameters. 

.EXAMPLE 
Get the message body from a Service Bus Message. 

PS > Get-Message | Get-MessageBody; 
I am a message body from ServiceBus with an arbitrary content. 

Attention: 
Throws an exception if the body already consumed (called more then once). 
Exception: "The message body cannot be read multiple times. To reuse it store the value after reading." 

#>
[CmdletBinding(
    HelpURI = 'http://dfch.biz/biz/dfch/PS/AzureServiceBus/Client/'
    ,
    SupportsShouldProcess = $true
    ,
    ConfirmImpact = "Low"
)]
[OutputType([String])]
Param 
(
    # [Required] Service Bus Message
    [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
    [alias("Message")]
    [Microsoft.ServiceBus.Messaging.BrokeredMessage] $InputObject
)

BEGIN 
{
    $datBegin = [datetime]::Now;
    [string] $fn = $MyInvocation.MyCommand.Name;
    Log-Debug $fn ("CALL.") -fac 1;

}
# BEGIN 

PROCESS 
{

[boolean] $fReturn = $false;

try 
{
    # Parameter validation
    #N/A

    # Get ValueFromPipeline
    $OutputObject = @();    
    foreach($Object in $InputObject) {
        if($PSCmdlet.ShouldProcess($Object)) {

            # Retry handling
            $Retry = 2;
            $RetryInterval = 1;
            for($c = 0; $c -le $Retry; $c++)
            {
                try
                {
                    # Get Message Body
                    $OutputParameter = Invoke-GenericMethod -InputObject $Object -MethodName 'GetBody' -GenericType 'String';
                    break;
                }
                catch
                {
                    # Throw execption
                    if ( $_.Exception.Message -match 'The message body cannot be read multiple times.' )
                    {
                        $msg = $_.Exception.Message;
                        $e = New-CustomErrorRecord -m $msg -cat InvalidData -o $Object;
                        $PSCmdlet.ThrowTerminatingError($e);
                    }
                    Log-Debug $fn ("[{0}/{1}] Retrying operation [{2}]" -f $c, $Retry, $fn);
                    Start-Sleep -Seconds $RetryInterval;
                    $RetryInterval *= 2;
                    continue;
                }
            }
            $OutputObject += $OutputParameter;
            $fReturn = $true;

        } # if
    } # foreach

    # Set output depending is ValueFromPipeline
    if ( $OutputObject.Count -gt 1 )
    {
        $OutputParameter = $OutputObject[0];
    }
    else
    {
        $OutputParameter = $OutputObject;
    }

}
catch 
{
    if($gotoSuccess -eq $_.Exception.Message) 
    {
            $fReturn = $true;
    } 
    else 
    {
        [string] $ErrorText = "catch [$($_.FullyQualifiedErrorId)]";
        $ErrorText += (($_ | fl * -Force) | Out-String);
        $ErrorText += (($_.Exception | fl * -Force) | Out-String);
        $ErrorText += (Get-PSCallStack | Out-String);

        if($_.Exception -is [System.Net.WebException]) 
        {
            Log-Critical $fn "Login to Uri '$Uri' with Username '$Username' FAILED [$_].";
            Log-Debug $fn $ErrorText -fac 3;
        }
        else 
        {
            Log-Error $fn $ErrorText -fac 3;
            if($gotoError -eq $_.Exception.Message) 
            {
                Log-Error $fn $e.Exception.Message;
                $PSCmdlet.ThrowTerminatingError($e);
            } 
            elseif($gotoFailure -ne $_.Exception.Message) 
            { 
                Write-Verbose ("$fn`n$ErrorText"); 
            } 
            else 
            {
                # N/A
            }
        }
        $fReturn = $false;
        $OutputParameter = $null;
    }
}
finally 
{
    # Clean up
    # N/A
}
return $OutputParameter;

}
# PROCESS

END 
{
    $datEnd = [datetime]::Now;
    Log-Debug -fn $fn -msg ("RET. fReturn: [{0}]. Execution time: [{1}]ms. Started: [{2}]." -f $fReturn, ($datEnd - $datBegin).TotalMilliseconds, $datBegin.ToString('yyyy-MM-dd HH:mm:ss.fffzzz')) -fac 2;
}
# END

} # function

if($MyInvocation.ScriptName) { Export-ModuleMember -Function Get-MessageBody; }