I am new to PowerShell.
Trying to understand how to use ForEach-Object command to iterate through each database on a server.
However it only bring master database multiple times and doesn't seems to be iterating through the rest of them.
# generate list of databases to iterate through
$DB = Invoke-SqlCmd -ServerInstance databasecluster -Database master -Query "SELECT [name] AS [Database] FROM sys.databases ORDER BY 1 DESC;"
$Query = "select DB_name();"
$DB | ForEach-Object{
$DB = "$_";
Invoke-Sqlcmd -Query $Query -ServerInstance myinstance;
}
What am I missing here?
UPDATE
PS C:\> $DB = Invoke-SqlCmd -ServerInstance myinstance -Database master -Query "SELECT [name] AS [Database] FROM sys.databases ORDER BY 1 DESC;"
>> $Query = "select DB_name();"
>> $DB | ForEach-Object{
>> $DB = "$_";
>> Invoke-Sqlcmd -ServerInstance myinstance -Database $DB -Query $Query
>> }
Error
*Invoke-Sqlcmd : Cannot open database "System.Data.DataRow" requested by the login. The login failed.
Login failed for user 'domain\username'.
At line:5 char:14
+ ... Invoke-Sqlcmd -ServerInstance myinstance -Database $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand*
SELECT DB_NAME()is going to return is the name of the database you connected to. If you want the names of all the databases on the instance have a look atsys.databases.-Databaseparameter on your secondInvoke-SqlCmdcall, so it will be using whatever the default database of your login is... which is probablymaster.System.Data.DataRowerror. Running code on local, I can connect without supplying credentials, however error indicatesLogin failedERRORLOGfile for the actual reason as to why the login failed. Unless your login is a member of sysadmins in SQL Server it's likely that it doesn't have access to all databases hosted by the instance.$DBobject is an array of objects of typesSystem.Data.DataRow. Try$_.Database(the name you gave the column in your query) to retrieve the values