我的目标是分配返回给变量的结果的值:
$sqlConnection = New-Object System.Data.sqlClient.sqlConnection $sqlConnection.ConnectionString = "Server=HOME\sqlEXPRESS;Database=master;Integrated Security=True" $sqlCmd = New-Object System.Data.sqlClient.sqlCommand $sqlCmd.CommandText = "select name from sysdatabases where name = 'tempdb'" $sqlCmd.Connection = $sqlConnection $sqlAdapter = New-Object System.Data.sqlClient.sqlDataAdapter $sqlAdapter.SelectCommand = $sqlCmd $DataSet = New-Object System.Data.DataSet $sqlAdapter.Fill($DataSet) $sqlConnection.Close() $DataSet.Tables[0]
返回的值显然应该是’tempdb’,那么如何将它分配给一个变量呢?
Write-output "Database is " $variablename
解决方法
$sqlConnection = New-Object System.Data.sqlClient.sqlConnection $sqlConnection.ConnectionString = "Server=HOME\sqlEXPRESS;Database=master;Integrated Security=True" $sqlConnection.Open() $sqlCmd = New-Object System.Data.sqlClient.sqlCommand $sqlCmd.CommandText = "select name from sysdatabases where name = 'tempdb'" $sqlCmd.Connection = $sqlConnection $dbname = $sqlCmd.ExecuteScalar() $sqlConnection.Close() Write-output "Database is " $dbname