I am trying to get multiple stored procedures, each out outputting certain results with varying column names.
I have managed to get the script to parse through each query however it just lumps all the results into one file. Is there anyway to have it generate the output (specifically via Export-CSV for formatting reasons) for each query in a separate file?
## DB Variables
$ServerName = "vLonMhDb2012-1"
$username = "sa"
$passwordfile = "\vlonmhapp2012-1APX$autoScriptsAPXSA_PasswordSecurestring.txt"
$SSPassword = cat $Passwordfile | convertto-securestring
$PSCredential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$SSPassword
$DBPassword = $PSCredential.GetNetworkCredential().Password
$DataBase = "APXFirm"
$queries = @("set nocount on;EXEC [APXFirm].[APXUserCustom].[pReconPortfolioSFIM] @portfolios='@CUST_Recon_UBSLondon'",
"set nocount on;EXEC [APXFirm].[APXUserCustom].[pReconSecuritySFIM] @Portfolios='@CUST_Recon_UBSLondon'",
"set nocount on;EXEC [APXFirm].[APXUserCustom].[pReconAppraisalSFIM] @Portfolios='@CUST_Recon_UBSLondon', @DATE = '{yest}', @UseSettlementDate = 0, @AccruedInterestID = 3",
"set nocount on;EXEC [APXFirm].[APXUserCustom].[pReconCashSFIM] @Portfolios='@CUST_Recon_UBSLondon', @DATE = '{yest}', @UseSettlementDate = 0, @AccruedInterestID = 3",
"set nocount on;EXEC [APXFirm].[APXUserCustom].[pReconTransactionHistoryAOSEMEA_181] @IsFromDataLoad=1, @IsUseStoredAuditEventID=1, @PortfolioBaseCode='@CUST_Recon_UBSLondon', @UseSettleDate=0, @StartDate='{tdly}', @EndDate='{toda}'"
)
##------------------------------------------------------------------
## Run Stored Proc
##------------------------------------------------------------------
foreach ($query in $queries)
{Invoke-SqlCmd -ServerInstance $ServerName -QueryTimeout 0 -Database $DataBase -Credential $PSCredential -Query $query -Verbose *>> "C:temp$CurrentTime.txt"}
So far only using -verbose *>> do i actually get the results from all stored procedures but of course they are lumped into one text file.
I have tried {Invoke-SqlCmd -ServerInstance $ServerName -QueryTimeout 0 -Database $DataBase -Credential $PSCredential -Query $query | Export-Csv ($Outputpath + $CurrentTime + ".csv")}
But I believe output does not go to pipeline in a foreach loop so that’s a no go.
Any ideas would be most welcome.
2
In the end piping every query result to a variable and then export-csv piped from that variable result does the intended of creating a csv with each query’s output.
foreach ($query in $queries) {
$returnresults = Invoke-SqlCmd -ServerInstance $ServerName -QueryTimeout 0 -Database $DataBase -Credential $PSCredential -Query $query
$returnresults | Export-Csv ($Outputpath + $query.Substring(47,14) + “” + $CurrentDate + “” + $CurrentTime + “.csv”)
}