I'm trying to properly capture output from SQLCMD in SQL Server 2012.
Here is the PS script:
$dbname = "MyDB"
$InstanceTarget = "localhost\SQLEXPRESS"
$FixOrphansSQL=@"
WITH login_CTE (name, type, sid)
As
(
Select name, type, sid from sys.database_principals where type = 'S'
)
select 'ALTER USER '+a.name+' WITH LOGIN ='+a.name As Fixusers from sys.server_principals a JOIN login_CTE b ON a.sid <> b.sid and a.name = b.name COLLATE Latin1_General_CI_AS
GO
"@
$RepairOrphansSQL = sqlcmd -S $InstanceTarget -Q $FixOrphansSQL -d $dbname
sqlcmd -S $InstanceTarget -Q $RepairOrphansSQL -d $dbname
If I run this
sqlcmd -S $InstanceTarget -Q $FixOrphansSQL -d $dbname
it works and the result is the script commands (on separate lines) to fix the orphaned users – but with some extra characters:
(lots of dashes -----------------)
ALTER USER InsightETLUser WITH LOGIN =InsightETLUser
ALTER USER APSDT_CDLinkedServerUser WITH LOGIN =APSDT_CDLinkedServerUser
(2 rows affected)
When I run
$RepairOrphansSQL = sqlcmd -S $InstanceTarget -Q $FixOrphansSQL -d $dbname
nothing gets captured into $RepairOrphansSQL.
sqlcmd, just useInvoke-Sqlcmdthen it will be output as an data table. If you want just the output as strings just pipe it toselect -ExpandProperty Fixusers.