Не удается найти перегрузку для «ExecuteQuery» и количество аргументов: «1» - PullRequest
0 голосов
/ 17 октября 2019

строгий текст Не удается найти перегрузку для "ExecuteQuery" и счетчика аргументов: "1". В C: \ Program Files \ WindowsPowerShell \ Modules \ AzureRmStorageTable \ 1.0.0.23 \ AzureRmStorageTableCoreHelper.psm1: 369 char: 2 + $ result = $ table.CloudTable.ExecuteQuery ($ tableQuery) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: NotSpecified: (:) [], MethodException + FullyQualifiedErrorId: MethodCountCouldNotFindBest

Не удается найти перегрузку для «Execute» и счетчика аргументов: «1». В C: \ Program Files \ WindowsPowerShell \ Modules \ AzureRmStorageTable \ 1.0.0.23 \ AzureRmStorageTableCoreHelper.psm1: 191 char: 11 + ... return ($ table.CloudTable.Execute ((invoke-expression "[Microsoft ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: NotSpecified: (:) [], MethodException + FullyQualifiedErrorId: MethodCountCouldNotFindBest

Невозможно найти перегрузку для «Execute» и количества аргументов: «1». В строке: 1 символ: 1 + [Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity, Microsoft.Wi ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: NotSpecified: (:) [], MethodException + FullyQualifiedErrorId: MethodCountCouldNotFindBest

ЭТО ТАКОЕ, ЧТО AzureRmStorageTableCoreHelper LOOKS LIKE <# .SYNOPSIS AzureRmStorageTableCoreCelHoreHerperTableCoreHelper.psm1 - связанные с классом класса. Модуль hell, содержащий все функции, связанные с манипулированием строками / сущностями таблицы хранения Azure. .NOTES Убедитесь, что установлен последний модуль Azure PowerShell, поскольку у нас есть зависимость от Microsoft.WindowsAzure.Storage.dll и Microsoft.WindowsAzure.Commands.Common.Storage.dll. </p>

If running this module from Azure Automation, please make sure you check out this blog post for more information:
https://blogs.technet.microsoft.com/paulomarques/2017/01/17/working-with-azure-storage-tables-from-powershell/

>

Требуется -Modules Azure.Storage, AzureRm.Profile, AzureRm.Storage, AzureRM.Resources

Функции модуля

функция GetLatestFullAssemblyName {параметр ([строка] $ dllName)

# getting list of all assemblies
$assemblies = [appdomain]::currentdomain.getassemblies() | Where-Object {$_.location -like "*$dllName"} 
if ($assemblies -eq $null)
{
    throw "Could not identify any assembly related to DLL named $dllName"
}

$sanitazedAssemblyList = @()
foreach ($assembly in $assemblies)
{
    [version]$version = $assembly.fullname.split(",")[1].split("=")[1]
    $sanitazedAssemblyList += New-Object -TypeName psobject -Property @{"version"=$version;"fullName"=$assembly.fullname}
}

return ($sanitazedAssemblyList | Sort-Object version -Descending)[0]

}

Получение последней версии Microsoft.WindowsAzure.Storage.dll полное имя сборки

$ assemblySN = (GetLatestFullAssemblyName -dllName "Microsoft.WindowsAzure.Storage.dll"). Полное имя

function Test-AzureStorageTableEmptyKeys {[CmdletBinding ()] param ([строка] $ partitionKey, [String] $ rowKey)

$cosmosDBEmptyKeysErrorMessage = "Cosmos DB table API does not accept empty partition or row keys when using CloudTable.Execute operation, because of this we are disabling this capability in this module and it will not proceed." 

if ([string]::IsNullOrEmpty($partitionKey) -or [string]::IsNullOrEmpty($rowKey))
{
    Throw $cosmosDBEmptyKeysErrorMessage
}

}

функция Get-AzureStorageTableTable {<# .SYNOPSIS Получает объект Table, он может быть из таблицы хранения Azure или из базы данных Cosmos в поддержке предварительного просмотра. .DESCRIPTION Получает объект Table, он может быть из таблицы хранения Azure или из базы данных Cosmos в поддержке предварительного просмотра. .PARAMETER resourceGroup Группа ресурсов, в которой находится учетная запись хранения Azure или база данных Cosmos .PARAMETER tableName Имя таблицы для извлечения .PARAMETER storageAccountName Имя учетной записи хранения, в которой находится таблица .EXAMPLE # Получение объекта таблицы хранения $ resourceGroup = "myResourceGroup" $ storageAccount ="myStorageAccountName" $ ​​tableName = "table01" $ table = Get-AzureStorageTabletable -resourceGroup $ resourceGroup -tableName $ tableName -storageAccountName $ storageAccount #> [CmdletBinding ()] param ([Параметр (ParameterSetName = "AzureRmable) = $ AzureRmableT] [string] $ resourceGroup,

    [Parameter(Mandatory=$true)]
    [String]$tableName,

    [Parameter(ParameterSetName="AzureRmTableStorage",Mandatory=$true)]
    [Parameter(ParameterSetName="AzureTableStorage",Mandatory=$true)]
    [String]$storageAccountName
)

$nullTableErrorMessage = [string]::Empty

switch ($PSCmdlet.ParameterSetName)
{
    "AzureRmTableStorage"
        {
            $saContext = (Get-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccountName).Context    
            $nullTableErrorMessage = "Table $tableName could not be retrieved from Storage Account $storageAccountName on resource group $resourceGroupName"
        }
    "AzureTableStorage"
        {
            $saContext = (Get-AzureStorageAccount -StorageAccountName $storageAccountName).Context
            $nullTableErrorMessage = "Table $tableName could not be retrieved from Classic Storage Account $storageAccountName"
        }
}

[Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable]$table = Get-AzureStorageTable -Name $tableName -Context $saContext -ErrorAction SilentlyContinue

# Creating a new table if one does not exist
if ($table -eq $null)
{
    [Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable]$table = New-AzureStorageTable -Name $tableName -Context $saContext
}

# Checking if there a table got returned
if ($table -eq $null)
{
    throw $nullTableErrorMessage
}

# Returns the table object
return [Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable]$table

}

function Add-StorageTableRow {<# .SYNOPSIS Добавляет строку / сущность в указанную таблицу .DESCRIPTION Добавляет строку / сущность вуказанная таблица .PARAMETER Table Объект Table типа Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable, в который будет добавляться объект .PARAMETER PartitionKeyИдентифицирует раздел таблицы .PARAMETER RowKey Идентифицирует строку в разделе. Свойство HARtable таблицы PARAMETER со столбцами, которые будут частью сущности. Например, @ {"firstName" = "Paulo"; "lastName" = "Marques"} .PARAMETER UpdateExisting Указывает, что команда должна обновить существующую строку, если такая найдена с помощью partitionKey и rowKey. Если не найдено, добавляется новая строка. .EXAMPLE # Добавление строки $ saContext = (Get-AzureRmStorageAccount -ResourceGroupName $ resourceGroup -Name $ storageAccount) .Context $ table = Get-AzureStorageTable -Name $ tableName -Context $ saContext Add-StorageTableRow -table $ table -partey $ table -parteyrowKey ([guid] :: NewGuid (). tostring ()) -property @ {"firstName" = "Paulo"; "lastName" = "Costa"; "role" = "Presenter"} #> [CmdletBinding ()]param ([Parameter (Mandatory = $ true)] $ table,

    [Parameter(Mandatory=$true)]
    [AllowEmptyString()]
    [String]$partitionKey,

    [Parameter(Mandatory=$true)]
    [AllowEmptyString()]
    [String]$rowKey,

    [Parameter(Mandatory=$false)]
    [hashtable]$property,
[Switch]$UpdateExisting
)

# Creates the table entity with mandatory partitionKey and rowKey arguments
$entity = New-Object -TypeName "Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity,$assemblySN" -ArgumentList $partitionKey, $rowKey

# Adding the additional columns to the table entity
foreach ($prop in $property.Keys)
{
    if ($prop -ne "TableTimestamp")
    {
        $entity.Properties.Add($prop, $property.Item($prop))
    }
}
    if($UpdateExisting)
{
    return ($table.CloudTable.Execute((invoke-expression "[Microsoft.WindowsAzure.Storage.Table.TableOperation,$assemblySN]::insertorreplace(`$entity)")))
}
else
{
    return ($table.CloudTable.Execute((invoke-expression "[Microsoft.WindowsAzure.Storage.Table.TableOperation,$assemblySN]::insert(`$entity)")))
}

}

function Get-PSObjectFromEntity {# Internal function # Преобразует объекты, выводимые из метода таблицы ExecuteQuery, вмассив объектов PowerShell

[CmdletBinding()]
param
(
    [Parameter(Mandatory=$true)]
    $entityList
)

$returnObjects = @()

if (-not [string]::IsNullOrEmpty($entityList))
{
    foreach ($entity in $entityList)
    {
        $entityNewObj = New-Object -TypeName psobject
        $entity.Properties.Keys | ForEach-Object {Add-Member -InputObject $entityNewObj -Name $_ -Value $entity.Properties[$_].PropertyAsObject -MemberType NoteProperty}

        # Adding table entity other attributes
        Add-Member -InputObject $entityNewObj -Name "PartitionKey" -Value $entity.PartitionKey -MemberType NoteProperty
        Add-Member -InputObject $entityNewObj -Name "RowKey" -Value $entity.RowKey -MemberType NoteProperty
        Add-Member -InputObject $entityNewObj -Name "TableTimestamp" -Value $entity.Timestamp -MemberType NoteProperty
        Add-Member -InputObject $entityNewObj -Name "Etag" -Value $entity.Etag -MemberType NoteProperty

        $returnObjects += $entityNewObj
    }
}

return $returnObjects

}

function Get-AzureStorageTableRowAll {<# .SYNOPSIS Возвращает все строки / объекты из таблицы хранения - без фильтрации .DESCRIPTION Возвращает все строки / объекты изтаблица хранения - без фильтрации .PARAMETER Таблица Объект таблицы типа Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable для получения объектов .EXAMPLE # Gettinвсе строки([Parameter (Mandatory = $ true)] $ table) </p>

# No filtering

$tableQuery = New-Object -TypeName "Microsoft.WindowsAzure.Storage.Table.TableQuery,$assemblySN"
$result = $table.CloudTable.ExecuteQuery($tableQuery)

if (-not [string]::IsNullOrEmpty($result))
{
    return (Get-PSObjectFromEntity -entityList $result)
}

}

function Get-AzureStorageTableRowByPartitionKey {<# .SYNOPSIS Возвращает одну или несколько строк / сущностей на основе ключа разделения. ОПИСАНИЕ Возвращает одну или несколько строк / сущностей на основе ключа раздела .PARAMETER Таблица Таблица Объект типа Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable для извлечения сущностей .PARAMETER PartitionKey Идентифицирует раздел таблицы .EXAMPLE # Получение строк по ключу раздела$ saContext = (Get-AzureRmStorageAccount -ResourceGroupName $ resourceGroup -Name $ storageAccount) .Context $ table = Get-AzureStorageTable -Name $ tableName -Context $ saContext Get-AzureStorageTableRowByPartitionKey -table $ table -part $ionKey #> [CmdletBinding ()] param ([Parameter (Mandatory = $ true)] $ table,

    [Parameter(Mandatory=$true)]
    [AllowEmptyString()]
    [string]$partitionKey
)

# Filtering by Partition Key


$tableQuery = New-Object -TypeName "Microsoft.WindowsAzure.Storage.Table.TableQuery,$assemblySN"

[string]$filter = `
    [Microsoft.WindowsAzure.Storage.Table.TableQuery]::GenerateFilterCondition("PartitionKey",`
    [Microsoft.WindowsAzure.Storage.Table.QueryComparisons]::Equal,$partitionKey)

$tableQuery.FilterString = $filter

$result = $table.CloudTable.ExecuteQuery($tableQuery)

if (-not [string]::IsNullOrEmpty($result))
{
    return (Get-PSObjectFromEntity -entityList $result)
}

}

function Get-AzureStorageTableRowByColumnName {<# .SYNOPSIS Возвращает один илибольше строк / сущностей на основе указанного столбца и его значения .DESCRIPTION Возвращает одну или несколько строк / сущностей на основе указанного столбца и его значения .PARAMETER Таблица Объект таблицы типа Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable toполучить сущности .PARAMETER ColumnName Имя столбца для сравнения значения со значением .PARAMETER Value, которое будет найдено в определенном столбце. Оператор PARAMETER Поддерживается оператор сравнения. Допустимые значения: «Равно», «GreaterThan», «GreaterThanOrEqual», «LessThan», «LessThanOrEqual», «NotEqual» .EXAMPLE # Получение строки по имениКонтекст $ table = Get-AzureStorageTable -Name $ tableName -Context $ saContext Get-AzureStorageTableRowByColumnName -table $ table -columnName "firstName" -value "Paulo" -operator Equal #> [CmdletBinding ()] param ([Параметр (обязательный) = обязательный $правда)]$ table,

    [Parameter(Mandatory=$true)]
    [string]$columnName,

    [Parameter(ParameterSetName="byString",Mandatory=$true)]
    [AllowEmptyString()]
    [string]$value,

    [Parameter(ParameterSetName="byGuid",Mandatory=$true)]
    [guid]$guidValue,

    [Parameter(Mandatory=$true)]
    [validateSet("Equal","GreaterThan","GreaterThanOrEqual","LessThan" ,"LessThanOrEqual" ,"NotEqual")]
    [string]$operator
)

# Filtering by Partition Key

$tableQuery = New-Object -TypeName "Microsoft.WindowsAzure.Storage.Table.TableQuery,$assemblySN"

if ($PSCmdlet.ParameterSetName -eq "byString") {
    [string]$filter = `
        [Microsoft.WindowsAzure.Storage.Table.TableQuery]::GenerateFilterCondition($columnName,[Microsoft.WindowsAzure.Storage.Table.QueryComparisons]::$operator,$value)
}

if ($PSCmdlet.ParameterSetName -eq "byGuid") {
    [string]$filter = `
        [Microsoft.WindowsAzure.Storage.Table.TableQuery]::GenerateFilterConditionForGuid($columnName,[Microsoft.WindowsAzure.Storage.Table.QueryComparisons]::$operator,$guidValue)
}

$tableQuery.FilterString = $filter

$result = $table.CloudTable.ExecuteQuery($tableQuery)


if (-not [string]::IsNullOrEmpty($result))
{
    return (Get-PSObjectFromEntity -entityList $result)
}

}

function Get-AzureStorageTableRowByCustomFilter {<# .SYNOPSIS Возвращает одну или несколько строк / сущностей на основе пользовательского фильтра. .DESCRIPTION Возвращает одну или несколько строк / сущностей на основе пользовательского фильтра. Этот пользовательский фильтр может быть создан с использованием класса Microsoft.WindowsAzure.Storage.Table.TableQuery или прямого текста. .PARAMETER Таблица Объект таблицы типа Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable для извлечения объектов .PARAMETER customFilter Пользовательская строка фильтра. .EXAMPLE # Получение строки по имени с использованием класса Microsoft.WindowsAzure.Storage.Table.TableQuery $ saContext = (Get-AzureRmStorageAccount -ResourceGroupName $ resourceGroup -Name $ storageAccount) .Context $ table = Get-AzureStorageTable -NamextName $ tableN$ saContext Get-AzureStorageTableRowByCustomFilter -table $ table -customFilter $ finalFilter .EXAMPLE # Получение строки по имени по текстовому фильтру напрямую (формат фильтра oData) $ saContext = (Get-AzureRmStorageAccount -ResourceGroupName $ resourceGroup -NameConchange $ tableAte $. = Get-AzureStorageTable -Name $ tableName -Context $ saContext Get-AzureStorageTableRowByCustomFilter -table $ table -customFilter "(firstName eq 'User1') и (lastName eq 'LastName1')" #> [CmdletBinding ()] param (Обязательный = $ true)] $ table,

    [Parameter(Mandatory=$true)]
    [string]$customFilter
)

# Filtering by Partition Key
$tableQuery = New-Object -TypeName "Microsoft.WindowsAzure.Storage.Table.TableQuery,$assemblySN"

$tableQuery.FilterString = $customFilter

$result = $table.CloudTable.ExecuteQuery($tableQuery)

if (-not [string]::IsNullOrEmpty($result))
{
    return (Get-PSObjectFromEntity -entityList $result)
}

}

function Update-AzureStorageTableRow {<# .SYNOPSIS Обновляет сущность таблицы .DESCRIPTION Обновляет сущность таблицы. Для работы с этим командлетом, вам нужно сначала получитьобъект с одним из доступных командлетов Get-AzureStorageTableRow, которые сохраняются в объекте, изменяют необходимые свойства и затем выполняют обновление, передавая этот измененный объект обратно, через конвейер или в качестве аргумента. Обратите внимание, что этот командлет принимает только одну сущность за выполнение. Этот командлет не может обновить ключ раздела и / или RowKey, поскольку он использует эти два значения, чтобы найти объект для его обновления. Если требуется выполнить эту операцию, удалите старый объект и добавьте новый с обновленными значениями. .PARAMETER Таблица Объект таблицы типа Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable, где существует сущность .PARAMETER Entity Объект / строка с новыми значениями для выполнения обновления. .EXAMPLE # Обновление сущности $ saContext = (Get-AzureRmStorageAccount -ResourceGroupName $ resourceGroup -Name $ storageAccount) .Context $ table = Get-AzureStorageTable -Name $ tableName -Context $ saContext [string] $ filter = [Microsoft.WindowsAzureS.Sext. .Table.TableQuery] :: GenerateFilterCondition ("firstName", [Microsoft.WindowsAzure.Storage.Table.QueryComparisons] :: Equal, "User1") $ person = Get-AzureStorageTableRowByCustomFilter -table $ table -customFilter $ filter $ person.lastName= "Новая Фамилия" $ человек |Update-AzureStorageTableRow -table $ table #> [CmdletBinding ()] param ([Parameter (Mandatory = $ true)] $ table,

    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    $entity
)

# Only one entity at a time can be updated
$updatedEntityList = @()
$updatedEntityList += $entity

if ($updatedEntityList.Count -gt 1)
{
    throw "Update operation can happen on only one entity at a time, not in a list/array of entities."
}

$updatedEntity = New-Object -TypeName "Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity,$assemblySN" -ArgumentList $entity.PartitionKey, $entity.RowKey

# Iterating over PS Object properties to add to the updated entity 
foreach ($prop in $entity.psobject.Properties)
{
    if (($prop.name -ne "PartitionKey") -and ($prop.name -ne "RowKey") -and ($prop.name -ne "Timestamp") -and ($prop.name -ne "Etag") -and ($prop.name -ne "TableTimestamp"))
    {
        $updatedEntity.Properties.Add($prop.name, $prop.Value)
    }
}

$updatedEntity.ETag = $entity.Etag

# Updating the dynamic table entity to the table
return ($table.CloudTable.Execute((invoke-expression "[Microsoft.WindowsAzure.Storage.Table.TableOperation,$assemblySN]::Replace(`$updatedEntity)")))

}

function Remove-AzureStorageTableRow {<# .SYNOPSIS Remove-AzureStorageTableRow - удаляет указанную строку таблицы .DESCRIPTION Remove-AzureStorageTableRow - удаляет указанную строку таблицы. Он принимает несколько удалений через конвейер при передаче объектов, возвращенных из доступных командлетов Get-AzureStorageTableRow, а также может удалять строку /сущность, напрямую использующая свойства Partition и Row Key. .PARAMETER Таблица Объект таблицы типа Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageTable, где сущность существует .PARAMETER Entity (ParameterSetName = byEntityPSObjectObject) Объект / строка с новыми значениями для новых значений для значенийудаление. .PARAMETER PartitionKey (ParameterSetName = byPartitionandRowKeys) Ключ раздела, к которому принадлежит объект. .PARAMETER RowKey (ParameterSetName = byPartitionandRowKeys) Ключ строки, который уникальным образом идентифицирует сущность в разделе. <br>.EXAMPLE # Удаление записи по сущности PS Object $ saContext = (Get-AzureRmStorageAccount -ResourceGroupName $ resourceGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup -Name $ storageGroup-.Name $ storageGroup -Name $ storageGroup-.Name $. Storage. $ table = Get-AzureStorageTable -Name $ tableName -Context $ saContext [string] $ filter1 = [Microsoft.WindowsAzure.Storage.Table.TableQuery] :: GenerateFilterCondition ("firstName", [Microsoft.WindowsAzure.Storage.Table.QueryComparisons]:: Equal, "Paulo") [string] $ filter2 = [Microsoft.WindowsAzure.Storage.Table.TableQuery] :: GenerateFilterCondition ("lastName", [Microsoft.WindowsAzure.Storage.Table.QueryComparisons] :: Equal, "Marques") [string] $ finalFilter = [Microsoft.WindowsAzure.Storage.Table.TableQuery] :: CombineFilters ($ filter1," and ", $ filter2) $ personToDelete = Get-AzureStorageTableRowByCustomFilter -table $ table -customFilter $ finalFilter $ personRemove-AzureStorageTableRow -table $ table .EXAMPLE # Удаление записи с использованием ключа ключа раздела и ключа строки напрямую $ saContext = (Get-AzureRmStorageAccount -ResourceGroupName $ resourceGroup -Name $ storageAccount) .Context $ table = Get-AzureStorageTable -Name $ tableName$ saContext Remove-AzureStorageTableRow -table $ table -partitionKey "TableEntityDemoFullList" -rowKey "399b58af-4f26-48b4-9b40-e28a8b03e867" .EXAMPLE # Удалить все$ table = Get-AzureStorageTable -Name $ tableName -Context $ saContext Get-AzureStorageTableRowAll -table $ table |Remove-AzureStorageTableRow -table $ table #> [CmdletBinding ()] param ([Параметр (обязательный = $ true)] $ table,

    [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="byEntityPSObjectObject")]
    $entity,

    [Parameter(Mandatory=$true,ParameterSetName="byPartitionandRowKeys")]
    [AllowEmptyString()]
    [string]$partitionKey,

    [Parameter(Mandatory=$true,ParameterSetName="byPartitionandRowKeys")]
    [AllowEmptyString()]
    [string]$rowKey
)

begin
{
    $updatedEntityList = @()
    $updatedEntityList += $entity

    if ($updatedEntityList.Count -gt 1)
    {
        throw "Delete operation cannot happen on an array of entities, altough you can pipe multiple items."
    }

    $results = @()
}

process
{
    if ($PSCmdlet.ParameterSetName -eq "byEntityPSObjectObject")
    {
        $partitionKey = $entity.PartitionKey
        $rowKey = $entity.RowKey
    }

    $entityToDelete = invoke-expression "[Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity,$assemblySN](`$table.CloudTable.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation,$assemblySN]::Retrieve(`$partitionKey,`$rowKey))).Result"

    if ($entityToDelete -ne $null)
    {
        $results += $table.CloudTable.Execute((invoke-expression "[Microsoft.WindowsAzure.Storage.Table.TableOperation,$assemblySN]::Delete(`$entityToDelete)"))
    }
}

end
{
    return ,$results
}

}

Псевдонимы

New-Alias ​​-Name Add-AzureStorageTableRow -Value Add-StorageTableRow

1 Ответ

0 голосов
/ 18 октября 2019

Насколько я понимаю, вы хотите использовать PowerShell для управления хранилищем таблиц Azure. Если это так, вы можете использовать модуль AzTable для его реализации.

Например

Install-Module -Name AzTable

$groupName=""
$StorageAccountName = ""
$StorageAccountKey = ""
$vaule=" "
$context = New-AzStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
$tables = Get-AzStorageTable -Context $context
Foreach($table in $tables){
    $table = Get-AzTableTable -storageAccountName $StorageAccountName -resourceGroup $groupName="" -TableName
    $entities=Get-AzTableRow -Table $table
    ForEach($e in $entities){
        $entity = New-Object Microsoft.Azure.Cosmos.Table.DynamicTableEntity($e.PartitionKey,$e.RowKey)
        $entity.Properties.Add("Name", $vaue)
        $table.Execute([Microsoft.Azure.Cosmos.Table.TableOperation]::InsertOrMerge($entity))
        Get-AzTableRow -Table $table -PartitionKey $e.PartitionKey -RowKey $e.RowKey
    }

}

Для получения более подробной информации, пожалуйста, обратитесь к https://docs.microsoft.com/en-us/azure/storage/tables/table-storage-how-to-use-powershell

...