是否可以在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"
}
有没有办法创建结构化变量,我可以创建那个和处理的数组?
答案 0 :(得分:4)
最简单的方法是使用哈希表并将它们转换为自定义对象:
$result = @()
for (... my loop ... ) {
... retrieve data ...
$props = @{ Databasename = $dbname; Tablename = $tname; Cols = $colarray }
$result += (new-object pscustomobject -prop $props)
}
答案 1 :(得分:3)
您需要查看Add-Member或Add-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