簡體   English   中英

PowerShell中的延遲管道執行?

[英]Deferred pipeline execution in powershell?

是否可以延遲管道執行或修改以前的管道? 我正在尋找的是與 ODATA 端點交互的能力。 我想使用標准(或自定義)powershell 命令來過濾數據,但我不想檢索整個列表。 例如

function Get-Records() {
    Invoke-RestMethod -Method Get -Uri $endpoint.Uri.AbsoluteUri ...
}

調用它可能會返回 500 多條記錄。 通常我不想檢索所有 500 條記錄,有時我會。 所以如果我需要所有 500 個,我可能只調用Get-Records但是如果我只想要特定的,我會想做

Get-Records | Where {$_.Name -eq 'me'}

以上仍然接收所有 500 條記錄,然后將它們過濾掉。 我會以某種方式希望Where {$_.Name -eq 'me'}將過濾器傳回前一個管道到Invoke-RestMethod並附加到 URI $filter=Name eq 'me'

您不能通過后處理過濾器(例如Where-Object追溯修改管道。

相反,您必須使用數據提供程序語法在源處進行過濾。

這是PowerShell的怎么內置的cmdlet,如Get-ChildItem做到這一點,通過[string] -typed -Filter參數

如果要將 PowerShell腳本塊作為過濾器傳遞,則必須自己將其轉換為提供程序的語法 -如果可能的話

PowerShell 表達式很少會與提供者的過濾器功能一對一映射,因此也許更好的方法是要求用戶直接使用提供者的語法

function Get-Records() {
  param(
   [Parameter(Mandatory)]
   [uri] $Uri
   ,
   [string] $Filter # Optional filter in provider syntax; e.g. "Name eq 'me'"
  )
    if ($Filter) { $Uri += '?$filter=' + $Filter }
    Invoke-RestMethod -Method Get -Uri $uri
}

# Invoke with a filter in the provider's syntax.
Get-Records "Name eq 'me'"

如果您確實希望用戶能夠傳遞腳本塊,您必須自己翻譯到提供程序語法並確保可以進行翻譯。

為了穩健地做到這一點,您必須處理腳本塊的 AST(抽象語法樹),它可以通過其.Ast屬性訪問,這是非常重要的。

如果您願意對允許用戶傳遞的表達式類型做出假設,則可以使用字符串解析,例如在以下簡單示例中:


function Get-Records {
  param(
   [Parameter(Mandatory)]
   [uri] $Uri
   ,
   [scriptblock] $FilterScriptBlock # Optional filter
  )
    if ($FilterScriptBlock) { 
      # Translate the script block' *string representation*
      # into the provider-native filter syntax.
      # Note: This is overly simplistic in that it simply removes '$_.'
      #       and '-' before '-eq'.
      $Uri += '?$filter=' + $FilterScriptBlock -replace '\$_\.' -replace '-(?=[a-z]+\b)'
    }
    Invoke-RestMethod -Method Get -Uri $Uri
}

# Invoke with a filter specified as a PowerShell script block.
Get-Records { $_.Name -eq 'me' }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM