1

是否可以在 powershell 中使用自定义数据类型?

我想要一个(结构化)变量,如下所示。跟随的东西在语法上不正确。我只想跟随三个变量。

Variable Databasedetails {
   string  DatabaseName
   string  TableName
   string[] columnNames 
}

如果 Powershell 可以做到这一点,那么我可以拥有单个变量数组,它可以帮助我轻松编写查询。

$Databasedetails = { "DataBaseName=DB-someX","TableName=TableX"," (ColumnNames={"Col1","col2"}" 
                    "DataBaseName=DB-someY","TableName=TableY"," (ColumnNames={"Col2","colN"}"
                  }

Foreach ($DBdetails in $DataBaseDetails)
  {
      $query= "SELECT [$DBdetails.$columnName] FROM [$DBdetails$DatabaseName].[dbo].[$DBdetails.$TableName]"
      invoke-sqlcmd -query $query -ServerInstance $srvInstance"
  }

有什么方法可以创建结构化变量,我可以创建该变量的数组并进行处理吗?

4

2 回答 2

5

最简单的方法是使用哈希表并将它们转换为自定义对象:

$result = @()
for (... my loop ... ) {
    ... retrieve data ...
    $props = @{ Databasename = $dbname; Tablename = $tname; Cols = $colarray }
    $result += (new-object pscustomobject -prop $props)
}
于 2012-07-03T15:50:45.757 回答
3

您将需要查看Add-MemberAdd-Type,后者仅在 Powershell 2.0 中。

$details = New-Object PsObject
             | Add-Member NoteProperty DatabaseName '' -pass 
             | Add-Member NoteProperty TableName '' -pass
             | Add-Member NoteProperty ColumnNames @() -pass

或添加类型

Add-Type 'public class DatabaseDetails { public string DatabaseName; public string TableName; public string[] ColumnNames; }' -Language CSharp

$details = New-Object DatabaseDetails
于 2012-07-03T13:17:40.877 回答