Stored procedure and data export automation - sql

I've created a stored procedure in Oracle SQL Developer that includes a set of queries. Every query returns a table that contains a large amount of data (over 2 million rows per table => the manual export already causes problems due to the size of data).
I want to automate the stored procedure and the export of every result table to a separate Excel sheet in one batch.
Thank you

I created a powershell script that exports all the tables of the specified user into separate csv files.
You can specify the desired list of tables in the query.
select TNAME from tab where tabtype='TABLE' and tname not like 'BIN$%'
If the table has 0 rows, then the csv file is not created.
In the script, you can specify the date format and code page for the strings.
$NLS_NUMERIC_CHARACTERS=".,"
$NLS_DATE_FORMAT="DD.MM.YYYY HH24:MI:SS"
$NLS_LANG="AMERICAN_AMERICA.UTF8"
The script exports all user tables to separate CSV files.
.\run_export_all_tables.ps1 -username SCOTT -password tiger -connect_string ORCL -csv_dir_path C:\upwork\powershell_sqlplus_export_csv\csv\ -log_file log_file.log
<#
.SYNOPSIS
The script exports all user tables to separate CSV files.
Author: Dmitry Demin dmitrydemin1973#gmail.com
.DESCRIPTION
In the script, the format for displaying the date and decimal separator is configured.
.PARAMETER username
Specify the username for example SCOTT
.PARAMETER password
Specify the password for example TIGER
.PARAMETER connect_string
Specify the connect_string(TNS alias) for connect to database from $ORACLE_HOME/network/admin/tnsnames.ora.
.PARAMETER csv_dir_path
Specify the csv directory for csv files
.PARAMETER log_file
Specify the log file for this script.
.EXAMPLE
The script exports all user tables to separate CSV files.
.\run_export_all_tables.ps1 -username SCOTT -password tiger -connect_string ORCL -csv_dir_path C:\upwork\powershell_sqlplus_export_csv\csv\ -log_file log_file.log
#>
param(
[string]$username = "scott",
[string]$password = "tiger",
[string]$connect_string = "esmd",
[string]$csv_dir_path = "C:\upwork\powershell_sqlplus_export_csv\csv\",
[string]$log_file = "C:\upwork\powershell_sqlplus_export_csv\log_file.log"
)
# Column separator for csv file
$COLSEP=";"
# NLS_NUMERIC_CHARACTERS
$NLS_NUMERIC_CHARACTERS=".,"
$NLS_DATE_FORMAT="DD.MM.YYYY HH24:MI:SS"
# Log file
$full_log_path=$log_file
# CSV directory
$full_csv_path=$csv_dir_path
#csv file extension
$csv_ext=".csv"
#Set NLS_LANG for session sqlplus
#"RUSSIAN_CIS.UTF8"
#"RUSSIAN_CIS.CL8MSWIN1251"
#"AMERICAN_AMERICA.UTF8"
#$NLS_LANG="RUSSIAN_CIS.CL8MSWIN1251"
$NLS_LANG="AMERICAN_AMERICA.UTF8"
#Set NLS_LANG for session sqlplus
[Environment]::SetEnvironmentVariable("NLS_LANG",$NLS_LANG , [System.EnvironmentVariableTarget]::PROCESS)
$env_path_NLS=[Environment]::GetEnvironmentVariable("NLS_LANG", [EnvironmentVariableTarget]::PROCESS)
echo "SET session NLS_LANG: $env_path_NLS" | tee-object -Append -filepath $full_log_path
$sqlQuery_show_user_tables =
#"
set heading off
set termout OFF
SET FEEDBACK OFF
SET TAB OFF
set pause off
set verify off
SET UNDERLINE OFF
set trimspool on
set timing off
set echo off
set linesize 1000
set pagesize 100
select TNAME from tab where tabtype='TABLE' and tname not like 'BIN$%'
;
exit
"#
$SqlQueryExportTable1 =
#"
set heading off
set termout OFF
SET FEEDBACK OFF
SET TAB OFF
set pause off
set verify off
SET UNDERLINE OFF
set trimspool on
set timing off
set echo off
set linesize 10000
set pagesize 0
SET COLSEP '$COLSEP'
ALTER SESSION SET NLS_NUMERIC_CHARACTERS='$NLS_NUMERIC_CHARACTERS';
ALTER SESSION SET NLS_DATE_FORMAT='$NLS_DATE_FORMAT';
select * from
"#
$SqlQueryExportTable2 =
#"
exit
"#
function Check_File
{
param (
[string]$pathfile
)
try {
$A=Get-Content -Path $pathfile -ErrorAction Stop
}
catch [System.UnauthorizedAccessException]
{
#Write-Host "File $pathfile is not accessible."
echo "File $pathfile is not accessible." | tee-object -Append -filepath $full_log_path
exit
}
catch [System.Management.Automation.ItemNotFoundException]
{
#Write-Host "File $pathfile is not found."
echo "File $pathfile is not found." | tee-object -Append -filepath $full_log_path
exit
}
catch {
Write-Host "File $pathfile. Other type of error was found:"
#Write-Host "Exception type is $($_.Exception.GetType().Name)"
echo "Exception type is $($_.Exception.GetType().Name)" | tee-object -Append -filepath $full_log_path
exit
}
}
echo "===========================================================================================" | tee-object -Append -filepath $full_log_path
$date_time_start = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$date_time_log = Get-Date -Format "yyyyMMddHHmmss"
Write-host "Script start time : $date_time_start "
try
{
echo "Script start time : $date_time_start ">>$full_log_path
}
catch {
Write-Host "Log File $full_log_path. Other type of error was found:"
Write-Host "Exception type is $($_.Exception.GetType().Name)"
exit
}
chcp 1251
$sqlQuery = $sqlQuery_show_user_tables
$sqlOutput = $sqlQuery | sqlplus -s $username/$password#$connect_string
$UserList =$sqlOutput| where {$_-notlike "" }
$i=1
echo "Found tables for export : " | tee-object -Append -filepath $full_log_path
foreach ($user_tab in $UserList)
{
echo " $i $user_tab" | tee-object -Append -filepath $full_log_path
$i=$i+1
}
foreach ($user_tab in $UserList)
{
$sqlQuery_show_table_all=""
$sqlQuery_show_table_all=$SqlQueryExportTable1+ $user_tab+ $SqlQueryExportTable2
$full_csv_path_file=$full_csv_path + $user_tab + "_" + $date_time_log + $csv_ext
echo "-------------------------------------------------------------------------------------------" | tee-object -Append -filepath $full_log_path
echo "For table : $user_tab will be created new csv file: $full_csv_path_file" | tee-object -Append -filepath $full_log_path
echo "Script will run for table: $user_tab " | tee-object -Append -filepath $full_log_path
$sqlOutput_tab = $sqlQuery_show_table_all | sqlplus -s $username/$password#$connect_string
$sqlOutput_count = $sqlOutput_tab.count
if ($sqlOutput_tab.count -gt 0)
{
Out-File -filepath $full_csv_path_file -append -inputobject $sqlOutput_tab -encoding default
echo "Exported rows: $sqlOutput_count " | tee-object -Append -filepath $full_log_path
}
else
{
echo "No exported rows: 0 row" | tee-object -Append -filepath $full_log_path
echo "$full_csv_path_file file not created " | tee-object -Append -filepath $full_log_path
}
echo "-------------------------------------------------------------------------------------------" | tee-object -Append -filepath $full_log_path
}
For example output script
Script start time : 2020-01-16 14:25:28
Found tables for export :
1 TEST_TABLE5
2 TEST_TABLE4
3 TEST_TABLE3
4 TEST_TABLE2
5 TEST_TABLE1
6 TEST2
7 TEST1
8 SALGRADE
9 EMP
10 DEPT
11 CL_TAB1
12 BONUS
-------------------------------------------------------------------------------------------
For table : TEST_TABLE5 will be created new csv file: .\csv\TEST_TABLE5_20200116142528.csv
Script will run for table: TEST_TABLE5
No exported rows: 0 row
.\csv\TEST_TABLE5_20200116142528.csv file not created
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : TEST_TABLE4 will be created new csv file: .\csv\TEST_TABLE4_20200116142528.csv
Script will run for table: TEST_TABLE4
No exported rows: 0 row
.\csv\TEST_TABLE4_20200116142528.csv file not created
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : TEST_TABLE3 will be created new csv file: .\csv\TEST_TABLE3_20200116142528.csv
Script will run for table: TEST_TABLE3
No exported rows: 0 row
.\csv\TEST_TABLE3_20200116142528.csv file not created
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : TEST_TABLE2 will be created new csv file: .\csv\TEST_TABLE2_20200116142528.csv
Script will run for table: TEST_TABLE2
No exported rows: 0 row
.\csv\TEST_TABLE2_20200116142528.csv file not created
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : TEST_TABLE1 will be created new csv file: .\csv\TEST_TABLE1_20200116142528.csv
Script will run for table: TEST_TABLE1
No exported rows: 0 row
.\csv\TEST_TABLE1_20200116142528.csv file not created
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : TEST2 will be created new csv file: .\csv\TEST2_20200116142528.csv
Script will run for table: TEST2
Exported rows: 213
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : TEST1 will be created new csv file: .\csv\TEST1_20200116142528.csv
Script will run for table: TEST1
Exported rows: 2
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : SALGRADE will be created new csv file: .\csv\SALGRADE_20200116142528.csv
Script will run for table: SALGRADE
Exported rows: 5
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : EMP will be created new csv file: .\csv\EMP_20200116142528.csv
Script will run for table: EMP
Exported rows: 14
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : DEPT will be created new csv file: .\csv\DEPT_20200116142528.csv
Script will run for table: DEPT
Exported rows: 7
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : CL_TAB1 will be created new csv file: .\csv\CL_TAB1_20200116142528.csv
Script will run for table: CL_TAB1
Exported rows: 4
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
For table : BONUS will be created new csv file: .\csv\BONUS_20200116142528.csv
Script will run for table: BONUS
No exported rows: 0 row
.\csv\BONUS_20200116142528.csv file not created
-------------------------------------------------------------------------------------------

To export a huge amount of data to an XLS file you can use:
https://www.oracle.com/webfolder/community/oracle_database/3784064.html
Also explained in
Create an Excel File (.xlsx) using PL/SQL

Related

Import CSV using PowerShell: date conversion

I'm importing CSV files to the MS SQL, and in different CSV files I have different date types. My code:
## Input Variables
$csvPath = "F:\Test\table.csv"
$csvDelimiter = ";"
$serverName = "name"
$databaseName = "dbname"
$tableSchema = "dbo"
$tableName = "dates"
$encoding = "windows-1251"
Import-Csv -Path $csvPath -encoding $encoding -Delimiter $csvDelimiter | Write-SqlTableData -ServerInstance $serverName -DatabaseName $databaseName -SchemaName $tableSchema -TableName $tableName -Force
And, for example, dates in my CSVs are like:
12JAN2021:18:03:41.000000
The problem here is that month written by the letters
or
17.04.2021
The problem here is that SQL read this like "mm.dd.yyyy" but it's "dd.mm.yyyy"
How can I improve my code so it can automatically read date correctly and write it to my date or datetime field in the destination table?
Thanks so much!
update CSV example:
product;product_id;product_nm;dttm
220;text;some text;12JAN2021:18:03:41.000000
220;text;some text;1JAN2021:18:03:41.000000
564;text;some text;16JAN2021:18:03:41.000000
I don't believe there is an "automated way" of parsing your CSVs if they all have a different DateTime format. I believe you would need to inspect each file to see if the format is valid (cast [datetime] directly to the string) or if they have a format that needs to be parsed.
In example, both provided dates on your question, need to be parsed and can be parsed with [datetime]::ParseExact(..):
[datetime]::ParseExact(
'12JAN2021:18:03:41.000000',
'ddMMMyyyy:HH:mm:ss.ffffff',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
[datetime]::ParseExact(
'17.04.2021',
'dd.MM.yyyy',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
If you need help "updating" the DateTime column from your CSV you would need to provide more details on that.
In example, the CSV provided in the question can be updated as follows:
# Here you would use this instead:
# $csv = Import-Csv path/to/csv.csv -Delimiter ';'
$csv = #'
product;product_id;product_nm;dttm
220;text;some text;12JAN2021:18:03:41.000000
220;text;some text;1JAN2021:18:03:41.000000
564;text;some text;16JAN2021:18:03:41.000000
'# | ConvertFrom-Csv -Delimiter ';'
foreach($line in $csv)
{
$line.dttm = [datetime]::ParseExact(
$line.dttm,
'dMMMyyyy:HH:mm:ss.ffffff',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
}
Now if we inspect the CSV it would look like this:
PS /> $csv | Format-Table
product product_id product_nm dttm
------- ---------- ---------- ----
220 text some text 01.12.2021
220 text some text 01.01.2021
564 text some text 01.16.2021
And all the process in pipeline would look as follows:
Import-Csv -Path $csvPath -Encoding $encoding -Delimiter $csvDelimiter |
ForEach-Object {
$_.dttm = [datetime]::ParseExact(
$_.dttm,
'dMMMyyyy:HH:mm:ss.ffffff',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
$_
} | Write-SqlTableData.....

PowerShell code to script out all SQL Server Agent jobs into a single file

I was trying to script out all the SQL Server Agent jobs for category 'Data Warehouse' into a single file
I was able to do it using PowerShell, where every single job creates a single file.
But I need one file for all the SQL Server Agent jobs under category ID = 100 (or Category : = 'Data Warehouse')
Code I'm currently using:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
$serverInstance = "APAAUHC7DB01VD"
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $serverInstance
$jobs = $server.JobServer.Jobs
#$jobs = $server.JobServer.Jobs | where-object {$_.category -eq "100"}
if ($jobs -ne $null)
{
$serverInstance = $serverInstance.Replace("\", "-")
ForEach ( $job in $jobs )
{
$FileName = "C:\SQLBackup\SQLJobs\" + $serverInstance + "_" + $job.Name + ".sql"
$job.Script() | Out-File -filepath $FileName
}
}
Give $FileName a single file name for the whole set. Then you can leave out the whole foreach block:
$FileName = "C:\SQLBackup\SQLJobs\whatever.sql"
$jobs | %{ $_.Script() } | Out-File -filepath $FileName

Pass a Variable from a Powershell Script to SQLPlus

I'm trying to pass a variable from my Powershell Script to SQLPlus.
I've defined my variable as $csvStorage (the file path to the folder "csv_files"):
Powershell Script:
# Set file path to C:\xxxx\xxxx\xxxx\xxxx\csv_files
$filePath = Split-Path -Path $directory -Parent
$csvStorage = Join-Path $filePath -ChildPath "csv_files"
I have then passed it as an argument to the SQL script:
Powershell Script:
# Run sql_queries.sql whilst passing C:\xxxx\xxxx\xxxx\xxxx\csv_files\ into the SQL script
$queryTables = "/c sqlplus $dbUsername/$dbPassword#$dbServiceName #$filePath $csvStorage"
&$sqlPlus $queryTables
Then finally, referenced the variable in my SQL using '&1':
SQL Script:
set null null
set heading on
set pagesize 50000
set termout on
spool &1\hc_actual_vs_shadow_inv.csv
SELECT *
FROM hc_actual_vs_shadow_inv
/
spool off
/
exit
However, the query is not being executed and no .csv file is outputted. But I can't see what I'm doing wrong. Any assistance would be much appreciated.
Thanks
<#
.SYNOPSIS
This script executes all sql files from the specified directory and creates separate csv files in a specified directory.
Author: Dmitry Demin dmitrydemin1973#gmail.com
.DESCRIPTION
In the script, the format for displaying the date and decimal separator is configured.
.PARAMETER username
Specify the username for example SCOTT
.PARAMETER password
Specify the password for example TIGER
.PARAMETER connect_string
Specify the connect_string(TNS alias) for connect to database from $ORACLE_HOME/network/admin/tnsnames.ora.
.PARAMETER sql_path
Specify the directory for executing sql scripts.
.PARAMETER csv_path
Specify the directory for output csv.
.PARAMETER log_path
Specify the log file.
.EXAMPLE
This script executes all sql files from the specified directory and creates separate csv files in a specified directory.
.\run_export_all_tables.ps1 -username SCOTT -password tiger -connect_string ORCL -sql_path C:\export\sql\ -csv_path C:\export\csv\
#>
param(
[string]$username = "scott",
[string]$password = "tiger",
[string]$connect_string = "192.168.0.166:1521/TEST",
[string]$sql_path="C:\upwork\powershell_sqlplus_export_csv\sql\",
[string]$csv_path="C:\upwork\powershell_sqlplus_export_csv\csv\",
[string]$log_path="C:\upwork\powershell_sqlplus_export_csv\log_file.log"
)
# Column separator for csv file
$COLSEP=";"
# NLS_NUMERIC_CHARACTERS
$NLS_NUMERIC_CHARACTERS=".,"
$NLS_DATE_FORMAT="DD.MM.YYYY HH24:MI:SS"
#[string]$connect_string = "server2003ora10:1521/ORCL"
# Log file
$full_sql_path=$sql_path
$full_csv_path=$csv_path
$full_log_path=$log_path
#csv file extension
$csv_ext=".csv"
#Set NLS_LANG for session sqlplus
#"RUSSIAN_CIS.UTF8"
#"RUSSIAN_CIS.CL8MSWIN1251"
#"AMERICAN_AMERICA.UTF8"
#$NLS_LANG="RUSSIAN_CIS.CL8MSWIN1251"
$NLS_LANG="AMERICAN_AMERICA.CL8MSWIN1251"
#$NLS_LANG="AMERICAN_AMERICA.UTF8"
#Set NLS_LANG for session sqlplus
[Environment]::SetEnvironmentVariable("NLS_LANG",$NLS_LANG , [System.EnvironmentVariableTarget]::PROCESS)
$env_path_NLS=[Environment]::GetEnvironmentVariable("NLS_LANG", [EnvironmentVariableTarget]::PROCESS)
echo "SET session NLS_LANG: $env_path_NLS" | tee-object -Append -filepath $full_log_path
$SqlQueryExportTable1 =
#"
set heading off
set termout OFF
SET FEEDBACK OFF
SET TAB OFF
set pause off
set verify off
SET UNDERLINE OFF
set trimspool on
set timing off
set echo off
set numwidth 30
set linesize 10000
set pagesize 0
SET COLSEP '$COLSEP'
ALTER SESSION SET NLS_NUMERIC_CHARACTERS='$NLS_NUMERIC_CHARACTERS';
ALTER SESSION SET NLS_DATE_FORMAT='$NLS_DATE_FORMAT';
"#
$SqlQueryExportTable2 =
#"
exit
"#
function Check_File
{
param (
[string]$pathfile
)
try {
$A=Get-Content -Path $pathfile -ErrorAction Stop
}
catch [System.UnauthorizedAccessException]
{
#Write-Host "File $pathfile is not accessible."
echo "File $pathfile is not accessible." | tee-object -Append -filepath $full_log_path
exit
}
catch [System.Management.Automation.ItemNotFoundException]
{
#Write-Host "File $pathfile is not found."
echo "File $pathfile is not found." | tee-object -Append -filepath $full_log_path
exit
}
catch {
Write-Host "File $pathfile. Other type of error was found:"
#Write-Host "Exception type is $($_.Exception.GetType().Name)"
echo "Exception type is $($_.Exception.GetType().Name)" | tee-object -Append -filepath $full_log_path
exit
}
}
echo "===========================================================================================" | tee-object -Append -filepath $full_log_path
$date_time_start = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$date_time_log = Get-Date -Format "yyyyMMddHHmmss"
Write-host "Script start time : $date_time_start "
try
{
echo "Script start time : $date_time_start ">>$full_log_path
}
catch {
Write-Host "Log File $full_log_path. Other type of error was found:"
Write-Host "Exception type is $($_.Exception.GetType().Name)"
exit
}
#chcp 1251
$files_input = Get-Childitem -File $full_sql_path
foreach ($file_input in $files_input)
{
echo "Found SQL file $file_input " | tee-object -Append -filepath $full_log_path
$full_sql_path_file=$full_sql_path+$file_input
$user_tab= get-content -Path $full_sql_path_file | out-string
echo "Found SQL : $user_tab " | tee-object -Append -filepath $full_log_path
$sqlQuery_show_table_all=""
$sqlQuery_show_table_all=$SqlQueryExportTable1+ $user_tab+ $SqlQueryExportTable2
$full_csv_path_file=$full_csv_path + $file_input + "_" + $date_time_log + $csv_ext
echo "-------------------------------------------------------------------------------------------" | tee-object -Append -filepath $full_log_path
echo "For SQL file : $full_sql_path_file will be created new csv file: $full_csv_path_file" | tee-object -Append -filepath $full_log_path
echo "Script will run for SQL: $user_tab " | tee-object -Append -filepath $full_log_path
$sqlOutput_tab = $sqlQuery_show_table_all | sqlplus -s $username/$password#$connect_string
$sqlOutput_count = $sqlOutput_tab.count
if ($sqlOutput_tab.count -gt 0)
{
Out-File -filepath $full_csv_path_file -append -inputobject $sqlOutput_tab -encoding default
echo "Exported rows: $sqlOutput_count " | tee-object -Append -filepath $full_log_path
}
else
{
echo "No exported rows: 0 row" | tee-object -Append -filepath $full_log_path
echo "$full_csv_path_file file not created " | tee-object -Append -filepath $full_log_path
}
echo "-------------------------------------------------------------------------------------------" | tee-object -Append -filepath $full_log_path
}

Conflict with Get-Item

I have a line of code that has some conflict in it and I just cannot see what it is.
Here is the program
$Date = Get-Date -Format MM-dd-yyyy-HH-mm-ss-tt
<#*****SQL Session Variables*****#>
$Username = "sa"
$Password = "xyz" | ConvertTo-SecureString -asPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($Username,$Password)
$DatabaseNames = Invoke-SQLcmd -Query "Select * From sys.databases WHERE Name NOT LIKE '%Master%' AND Name NOT LIKE '%Tempdb%' AND Name NOT LIKE '%Model%' AND Name NOT LIKE '%Msdb%';" -ServerInstance "localhost" | Select Name -ExpandProperty Name
Write-Host "****Database Names****" -ForeGroundColor Red -BackGroundColor Black
$DatabaseNames
"`n`n"
<#****Get Database Size****#>
Push-Location
Import-Module sqlps -disablenamechecking
Invoke-Sqlcmd -Query "select name, physical_name, size * 8.0 / 1024 size from sys.master_files WHERE Type_Desc NOT LIKE '%LOG%' AND Name NOT LIKE '%Master%' AND Name NOT LIKE '%Tempdb%' AND Name NOT LIKE '%Model%' AND Name NOT LIKE '%Msdb%';" -ServerInstance "localhost" | Select #{Label="Database Name";Expression={$_.name}}, #{Label="Location";Expression={$_.physical_name}}, #{Label="SIze (MB)";Expression={$_.size}}
Pop-Location
"`n"
Start-Sleep 4
<#****Backup Databases****#>
ForEach ($DatabaseName in $DatabaseNames)
{
$SQLBackupPath1 = "C:\T2\SQlBackup\"
$SQLBackupPath2 = "$DatabaseName"
$SQLBackupPath3 = "_"
$SQLBackupPath4 = $Date
$SQLBackupPath5 = "_.bak"
$SQLBackupPath = $SQLBackupPath1 + $SQLBackupPath2 + $SQLBackupPath3 + $SQLBackupPath4 + $SQLBackupPath5
$SQLBackupPath
Backup-SQLDatabase -ServerInstance localhost -Database $DatabaseName -BackupFile $SQLBackupPath -Credential $Credentials
Write-Host "Database Backup of " -NoNewLine
Write-Host "$DatabaseName" -ForeGroundColor Red -BackGroundColor Black -NoNewLine
Write-Host " has been completed"
"`n"
}
<#****Delete Databases****#>
ForEach ($DatabaseName in $DatabaseNames)
{
Push-Location
Import-Module sqlps -disablenamechecking
Invoke-Sqlcmd -Query "EXEC msdb.dbo.sp_delete_database_backuphistory #database_name = N'$DatabaseName';" -ServerInstance "localhost"
Invoke-Sqlcmd -Query "USE [master];" -ServerInstance "localhost"
Invoke-Sqlcmd -Query "ALTER DATABASE [$DatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;" -ServerInstance "localhost"
Invoke-Sqlcmd -Query "DROP DATABASE [$DatabaseName];" -ServerInstance "localhost"
Pop-Location
Write-Host "Database: " -NoNewLine
Write-Host "$DatabaseName" -ForeGroundColor Red -BackGroundColor Black -NoNewLine
Write-Host " has been Dropped"
"`n"
}
Get-ChildItem -Path C:\T2\SQLBackup\ | Where-Object {$_.Name -match "ApOps*" } | Sort-Object LastWriteTime -Descending
If I move the final GetChildItem line under the first line $Date I get output. However if I use this in a loop or where it currently sits no results are returned. This makes me believe that there is some conflicting statement in the code. If so I cannot seem to find it and I am losing my mind looking for it. Please help.
You're being bitten by the output formatting, and being a bit careless with your output. Consider this, I'm in a directory with a couple of files:
List the files, simple and works fine:
PS D:\test> Get-ChildItem # list the files
Directory: D:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 02/11/2016 07:01 1640 log.txt
-a---- 02/11/2016 07:01 0 testfile
Output an empty string, then list the files, simple and works fine. One blank line extra at the start:
PS D:\test> ""; Get-ChildItem
Directory: D:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 02/11/2016 07:01 1640 log.txt
-a---- 02/11/2016 07:01 0 testfile
Get the string length, then list the files. Wait what? The output formatter is taking property you asked for from the first output it receives (string Length) and is then applying that to everything it receives (files) until the pipeline is empty:
PS D:\test> "" | select Length; Get-ChildItem # select string length, then...
Length # missing columns ??!!
------
0 # string length
1640 # file length
0 # file length
Get some property which doesn't exist, then list the files. This is the same idea, only this time it's not showing anything for the string or anything for the files, because Foobar doesn't exist on either type:
PS D:\test> "" | select Foobar; Get-ChildItem # select property which doesn't exist
Foobar
------
# ???? this is your "no output"
You are doing this kind of thing - sending mixed types to the output pipeline. They still go to the output, if you captured them in variables or wrote them to files the data would be there, but the output formatter which tries to work out how to display them on the console takes the first thing it gets and formats the output against that, assuming you'll have a consistent output. And the first complex objects it gets come from your code here:
Invoke-Sqlcmd -Query "select name, physical_name, size * 8.0 / 1024 size from sys.master_files WHERE Type_Desc NOT LIKE '%LOG%' AND Name NOT LIKE '%Master%' AND Name NOT LIKE '%Tempdb%' AND Name NOT LIKE '%Model%' AND Name NOT LIKE '%Msdb%';" -ServerInstance "localhost" | Select #{Label="Database Name";Expression={$_.name}}, #{Label="Location";Expression={$_.physical_name}}, #{Label="SIze (MB)";Expression={$_.size}}
# where you select these properties for display:
# Database Name, Location, Size (MB)
# None of these properties exist on files or directories,
# so they don't get shown on screen.
Fix:
$x = Invoke-SqlCmd ___
$y = Get-ChildItem
$x | Format-Table
$y | Format-Table
Or use more Write-Host, or output to files.

How can I have a powershell loop that echos echo on the same line?

Currently I have the follow ps that reads a list of user names and then echos it.
The username file is the following
username1
username2
username3
The ps script is the following
$userNames = (Get-Content usernames.txt)# | Sort-Object
$userID=0
$userNames.Count
echo "FROM table WHERE (userID ='"
For ($i =1; $i -le ($userNames.Count - 1); $i++)
{
echo $userNames[$userID] "' OR userID='"
$userID++
}
echo $userNames[$userNames.Count - 1] "'"
I am hoping to get this to echo (and eventually write to a text file) all on the same line.
FROM table WHERE (userID = 'username1' OR userID = 'username2' OR userID = 'username3'
How would I go about solving this?
What you are looking for is:
Write-Host "Blah" -NoNewLine
I would probably re-write the script like this to avoid having to use the For...Loop
$userNames = (Get-Content usernames.txt) | Sort-Object
$count = 0
Write-Host "FROM table WHERE (" -NoNewLine
$userNames |% {
Write-Host "userID='$_'" -NoNewLine
if(++$count -ne $userNames.Length){
Write-Host " OR " -NoNewLine
}
else {
Write-Host ")"
}
}
This script will also take advantage of another nice feature of PowerShell, which is variable substitution in string literals. For-EachObject automatically sets $_ to be the current object during the iteration, and PowerShell will automatically parse variables in string literals and substitute their values.
Also... I just realized the entire thing can be reduced to the following:
$userNames = (Get-Content usernames.txt) | Sort-Object |% { "'$_'" }
Write-Host "FROM table WHERE UserID in ($([String]::Join(",",$userNames)))"
Which will produce the following query:
FROM table WHERE UserID in ('username1','username2','username3')
This is a much more pleasant script and query in my opinion :)