考慮PowerShell腳本下面的代碼名爲NewDB.ps1
:爲什麼PowerShell不保留原生類型?
param ($i, $d)
Function New-Database
{
param ($instance, $name)
$db = New-Object Microsoft.SqlServer.Management.Smo.Database ($instance, $name)
try { $db.Create() }
catch [Exception] { $_.Exception | Format-list | Out-String ; exit }
$db.CreateDate.DateTime
$db.DatabaseOptions.RecoveryModel
return $db
}
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$sqlServer = new-Object Microsoft.SqlServer.Management.Smo.Server($i)
[Microsoft.SqlServer.Management.Smo.Database]$myDB = New-Database $sqlServer $d
我得到一個類型轉換錯誤:
PS C:\Users\moomin\Documents> .\NewDB.ps1 "(local)" "testDB"
Cannot convert the "System.Object[]" value of type "System.Object[]" to type
"Microsoft.SqlServer.Management.Smo.Database".
At C:\Users\moomin\Documents\NewDB.ps1:21 char:1
+ [Microsoft.SqlServer.Management.Smo.Database]$myDB = New-Database $sqlServer $d
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
如何從我的函數返回的對象返回作爲Microsoft.SqlServer.Management.Smo.Database
對象?我需要在功能之外做更多的事情。
UPDATE 當然,感謝@ mjolinor,這和我現在想要的完全一樣。順便說一句,它也適用於New-Database
在一個單獨的模塊(我如何實際實現它)。
param ($i, $d)
Function New-Database
{
param ($instance, $name)
$db = New-Object Microsoft.SqlServer.Management.Smo.Database ($instance, $name)
try { $db.Create() }
catch [Exception] { $_.Exception | Format-list | Out-String ; exit }
$db
}
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$sqlServer = new-Object Microsoft.SqlServer.Management.Smo.Server($i)
$myDB = New-Database $sqlServer $d
$myDB.CreateDate.DateTime
$myDB.DatabaseOptions.RecoveryModel
如果我有對象的數組返回,我可以檢查對象的數組,並與Smo.Database對象工作?在問題的更新中添加了我的完整解決方案。 –