eliminato SqlCommand
This commit is contained in:
parent
7faa1e8c82
commit
d490127154
@ -51,7 +51,7 @@ $config = @{
|
|||||||
SqlDir = Join-Path (Split-Path -Path $PSScriptRoot -Parent) "sql"
|
SqlDir = Join-Path (Split-Path -Path $PSScriptRoot -Parent) "sql"
|
||||||
}
|
}
|
||||||
|
|
||||||
$DBI = $DBBenvProd
|
$DBI = $DBStampeColl
|
||||||
$DBO = $DBStampeLoc
|
$DBO = $DBStampeLoc
|
||||||
# Esporta le variabili come variabili d'ambiente
|
# Esporta le variabili come variabili d'ambiente
|
||||||
$env:dbHostInput = $DBI.sqlServerName
|
$env:dbHostInput = $DBI.sqlServerName
|
||||||
|
@ -14,10 +14,8 @@ if (-not (Test-Path -Path $OutputPath)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Importa il modulo SqlServer se non è già caricato
|
# Carica l'assembly System.Data
|
||||||
if (-not (Get-Module -Name SqlServer)) {
|
Add-Type -AssemblyName System.Data
|
||||||
Import-Module SqlServer
|
|
||||||
}
|
|
||||||
|
|
||||||
# Definizione manuale dell'elenco delle tabelle da elaborare
|
# Definizione manuale dell'elenco delle tabelle da elaborare
|
||||||
# Formato: ogni elemento è un oggetto con proprietà DbName, SchemaName e TableName
|
# Formato: ogni elemento è un oggetto con proprietà DbName, SchemaName e TableName
|
||||||
@ -160,7 +158,13 @@ try {
|
|||||||
"@
|
"@
|
||||||
|
|
||||||
# Ottieni la struttura delle colonne
|
# Ottieni la struttura delle colonne
|
||||||
$columns = Invoke-Sqlcmd -ServerInstance $env:dbHostInput -Database $env:dbNameInput -Query $columnQuery -Username $env:dbUserInput -Password $env:dbPasswordInput -TrustServerCertificate
|
$connectionString = "Server=$($env:dbHostInput);Database=$($env:dbNameInput);User Id=$($env:dbUserInput);Password=$($env:dbPasswordInput);TrustServerCertificate=True"
|
||||||
|
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
||||||
|
$command = New-Object System.Data.SqlClient.SqlCommand($columnQuery, $connection)
|
||||||
|
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
|
||||||
|
$dataset = New-Object System.Data.DataSet
|
||||||
|
$adapter.Fill($dataset) | Out-Null
|
||||||
|
$columns = $dataset.Tables[0]
|
||||||
|
|
||||||
# Costruisci la CREATE TABLE
|
# Costruisci la CREATE TABLE
|
||||||
$createTableScript = "CREATE TABLE [$dbName].[$schemaName].[$tableName] (`n"
|
$createTableScript = "CREATE TABLE [$dbName].[$schemaName].[$tableName] (`n"
|
||||||
|
@ -5,14 +5,8 @@
|
|||||||
# Imposta il percorso di output nella cartella sql
|
# Imposta il percorso di output nella cartella sql
|
||||||
$OutputPath = Join-Path $env:workdir "transito"
|
$OutputPath = Join-Path $env:workdir "transito"
|
||||||
|
|
||||||
# Verifica e installa il modulo SqlServer se necessario
|
# Carica l'assembly System.Data
|
||||||
if (-not (Get-Module -ListAvailable -Name SqlServer)) {
|
Add-Type -AssemblyName System.Data
|
||||||
Write-Host "Installazione del modulo SqlServer..."
|
|
||||||
Install-Module -Name SqlServer -Force -AllowClobber -Scope CurrentUser
|
|
||||||
}
|
|
||||||
|
|
||||||
# Importa il modulo SqlServer
|
|
||||||
Import-Module SqlServer -DisableNameChecking
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Query per ottenere l'elenco degli oggetti
|
# Query per ottenere l'elenco degli oggetti
|
||||||
@ -35,7 +29,12 @@ try {
|
|||||||
|
|
||||||
# Esegui la query e salva i risultati
|
# Esegui la query e salva i risultati
|
||||||
$connectionString = "Server=$($env:dbHostInput);Database=$($env:dbNameInput);User Id=$($env:dbUserInput);Password=$($env:dbPasswordInput);TrustServerCertificate=True"
|
$connectionString = "Server=$($env:dbHostInput);Database=$($env:dbNameInput);User Id=$($env:dbUserInput);Password=$($env:dbPasswordInput);TrustServerCertificate=True"
|
||||||
$results = Invoke-Sqlcmd -ConnectionString $connectionString -Query $query
|
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
||||||
|
$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
|
||||||
|
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
|
||||||
|
$dataset = New-Object System.Data.DataSet
|
||||||
|
$adapter.Fill($dataset) | Out-Null
|
||||||
|
$results = $dataset.Tables[0]
|
||||||
|
|
||||||
# Prepara l'output
|
# Prepara l'output
|
||||||
$output = "Elenco oggetti del database $($env:DbName) su $($env:DbHostInput) il $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')`r`n"
|
$output = "Elenco oggetti del database $($env:DbName) su $($env:DbHostInput) il $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')`r`n"
|
||||||
|
@ -3,46 +3,27 @@ param(
|
|||||||
[string]$TableName
|
[string]$TableName
|
||||||
)
|
)
|
||||||
|
|
||||||
function Install-RequiredModules {
|
|
||||||
$requiredModule = "SqlServer"
|
|
||||||
|
|
||||||
if (-not (Get-Module -ListAvailable -Name $requiredModule)) {
|
|
||||||
Write-Host "Installazione modulo $requiredModule..."
|
|
||||||
try {
|
|
||||||
Install-Module -Name $requiredModule -Force -AllowClobber -Scope CurrentUser
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
Write-Error "Errore durante l'installazione del modulo $requiredModule. Eseguire PowerShell come amministratore e riprovare."
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Verifica e installa moduli necessari
|
|
||||||
Install-RequiredModules
|
|
||||||
|
|
||||||
# Importa configurazione
|
# Importa configurazione
|
||||||
. "$PSScriptRoot\conf.ps1"
|
. "$PSScriptRoot\conf.ps1"
|
||||||
|
|
||||||
|
# Carica l'assembly System.Data
|
||||||
|
Add-Type -AssemblyName System.Data
|
||||||
|
|
||||||
$OutputFile = Join-Path $PSScriptRoot "..\extract\$TableName.csv"
|
$OutputFile = Join-Path $PSScriptRoot "..\extract\$TableName.csv"
|
||||||
|
|
||||||
$Query = "SELECT * FROM $TableName"
|
$Query = "SELECT * FROM $TableName"
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Import SQL Server module if not already loaded
|
|
||||||
if (-not (Get-Module -Name SqlServer)) {
|
|
||||||
Import-Module SqlServer
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host "Connessione a $env:dbHostInput, database $env:dbNameInput..."
|
Write-Host "Connessione a $env:dbHostInput, database $env:dbNameInput..."
|
||||||
|
|
||||||
# Esegui la query e salva i risultati
|
# Crea la connessione e esegui la query
|
||||||
$result = Invoke-Sqlcmd -ServerInstance $env:dbHostInput `
|
$connectionString = "Server=$($env:dbHostInput);Database=$($env:dbNameInput);User Id=$($env:dbUserInput);Password=$($env:dbPasswordInput);TrustServerCertificate=True"
|
||||||
-Database $env:dbNameInput `
|
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
||||||
-Username $env:dbUserInput `
|
$command = New-Object System.Data.SqlClient.SqlCommand($Query, $connection)
|
||||||
-Password $env:dbPasswordInput `
|
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
|
||||||
-TrustServerCertificate `
|
$dataset = New-Object System.Data.DataSet
|
||||||
-Query $Query
|
$adapter.Fill($dataset) | Out-Null
|
||||||
|
$result = $dataset.Tables[0]
|
||||||
|
|
||||||
if ($result) {
|
if ($result) {
|
||||||
$result | Export-Csv -Path $OutputFile -NoTypeInformation -Delimiter ";" -Encoding UTF8
|
$result | Export-Csv -Path $OutputFile -NoTypeInformation -Delimiter ";" -Encoding UTF8
|
||||||
|
@ -15,10 +15,8 @@ $ViewOutputPath = Join-Path $BaseOutputPath "viste"
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Importa il modulo SqlServer se non è già caricato
|
# Carica l'assembly System.Data
|
||||||
if (-not (Get-Module -Name SqlServer)) {
|
Add-Type -AssemblyName System.Data
|
||||||
Import-Module SqlServer
|
|
||||||
}
|
|
||||||
|
|
||||||
# Query per estrarre stored procedures, funzioni e view
|
# Query per estrarre stored procedures, funzioni e view
|
||||||
$query = @"
|
$query = @"
|
||||||
@ -37,11 +35,17 @@ try {
|
|||||||
WHERE o.type IN ('P', 'FN', 'IF', 'TF', 'V')
|
WHERE o.type IN ('P', 'FN', 'IF', 'TF', 'V')
|
||||||
"@
|
"@
|
||||||
|
|
||||||
# Esegui la query
|
# Crea la connessione e esegui la query
|
||||||
$sqlObjects = Invoke-Sqlcmd -ServerInstance $env:dbHostInput -Database $env:dbNameInput -Query $query -Username $env:dbUserInput -Password $env:dbPasswordInput -MaxCharLength 1000000 -TrustServerCertificate
|
$connectionString = "Server=$($env:dbHostInput);Database=$($env:dbNameInput);User Id=$($env:dbUserInput);Password=$($env:dbPasswordInput);TrustServerCertificate=True"
|
||||||
|
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
||||||
|
$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
|
||||||
|
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
|
||||||
|
$dataset = New-Object System.Data.DataSet
|
||||||
|
$adapter.Fill($dataset) | Out-Null
|
||||||
|
$sqlObjects = $dataset.Tables[0]
|
||||||
|
|
||||||
# Funzione per pulire il nome del file
|
# Funzione per formattare il nome del file
|
||||||
function Clean-FileName {
|
function Format-FileName {
|
||||||
param([string]$name)
|
param([string]$name)
|
||||||
# Sostituisce caratteri non validi con underscore
|
# Sostituisce caratteri non validi con underscore
|
||||||
$invalidChars = [IO.Path]::GetInvalidFileNameChars()
|
$invalidChars = [IO.Path]::GetInvalidFileNameChars()
|
||||||
@ -55,8 +59,8 @@ try {
|
|||||||
|
|
||||||
# Per ogni oggetto trovato
|
# Per ogni oggetto trovato
|
||||||
foreach ($obj in $sqlObjects) {
|
foreach ($obj in $sqlObjects) {
|
||||||
$schemaName = Clean-FileName $obj.SchemaName
|
$schemaName = Format-FileName $obj.SchemaName
|
||||||
$objName = Clean-FileName $obj.ObjectName
|
$objName = Format-FileName $obj.ObjectName
|
||||||
$definition = $obj.ObjectDefinition
|
$definition = $obj.ObjectDefinition
|
||||||
|
|
||||||
# Determina il percorso di output basato sul tipo di oggetto
|
# Determina il percorso di output basato sul tipo di oggetto
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
# Importa configurazione
|
# Importa configurazione e assembly necessari
|
||||||
|
Add-Type -AssemblyName System.Web
|
||||||
. "$PSScriptRoot\conf.ps1"
|
. "$PSScriptRoot\conf.ps1"
|
||||||
|
|
||||||
$scriptName = $MyInvocation.MyCommand.Name
|
$scriptName = $MyInvocation.MyCommand.Name
|
||||||
@ -14,10 +15,8 @@ if (-not (Test-Path -Path $OutputPath)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Importa il modulo SqlServer se non è già caricato
|
# Carica l'assembly System.Data
|
||||||
if (-not (Get-Module -Name SqlServer)) {
|
Add-Type -AssemblyName System.Data
|
||||||
Import-Module SqlServer
|
|
||||||
}
|
|
||||||
|
|
||||||
# Query per estrarre la definizione delle tabelle
|
# Query per estrarre la definizione delle tabelle
|
||||||
$query = @"
|
$query = @"
|
||||||
@ -93,29 +92,24 @@ try {
|
|||||||
Write-Host "Eseguo query su $env:dbHostInput..."
|
Write-Host "Eseguo query su $env:dbHostInput..."
|
||||||
"Eseguo query su $env:dbHostInput..." | Out-File -FilePath $logFile -Append
|
"Eseguo query su $env:dbHostInput..." | Out-File -FilePath $logFile -Append
|
||||||
|
|
||||||
$sqlParams = @{
|
|
||||||
ServerInstance = $env:dbHostInput
|
|
||||||
Database = $env:dbNameInput
|
|
||||||
Query = $query
|
|
||||||
Username = $env:dbUserInput
|
|
||||||
Password = $env:dbPasswordInput
|
|
||||||
MaxCharLength = 1000000
|
|
||||||
TrustServerCertificate = $true
|
|
||||||
ConnectionTimeout = 30
|
|
||||||
EncryptConnection = $true
|
|
||||||
ApplicationIntent = 'ReadOnly'
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Write-Host "Tentativo di connessione a $($sqlParams.ServerInstance)..."
|
# Crea la connessione e esegui la query
|
||||||
$tables = Invoke-Sqlcmd @sqlParams
|
$connectionString = "Server=$($env:dbHostInput);Database=$($env:dbNameInput);User Id=$($env:dbUserInput);Password=$($env:dbPasswordInput);TrustServerCertificate=True;Connection Timeout=30"
|
||||||
|
Write-Host "Tentativo di connessione a $($env:dbHostInput)..."
|
||||||
|
|
||||||
|
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
||||||
|
$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
|
||||||
|
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
|
||||||
|
$dataset = New-Object System.Data.DataSet
|
||||||
|
$adapter.Fill($dataset) | Out-Null
|
||||||
|
$tables = $dataset.Tables[0]
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
Write-Error "Errore di connessione al database: $($_.Exception.Message)"
|
Write-Error "Errore di connessione al database: $($_.Exception.Message)"
|
||||||
Write-Host "Dettagli connessione:"
|
Write-Host "Dettagli connessione:"
|
||||||
Write-Host "Server: $($sqlParams.ServerInstance)"
|
Write-Host "Server: $($env:dbHostInput)"
|
||||||
Write-Host "Database: $($sqlParams.Database)"
|
Write-Host "Database: $($env:dbNameInput)"
|
||||||
Write-Host "Utente: $($sqlParams.Username)"
|
Write-Host "Utente: $($env:dbUserInput)"
|
||||||
throw
|
throw
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -150,20 +144,20 @@ try {
|
|||||||
Write-Host "Elaboro ${schemaName}.${tableName}..."
|
Write-Host "Elaboro ${schemaName}.${tableName}..."
|
||||||
"Elaboro ${schemaName}.${tableName}..." | Out-File -FilePath $logFile -Append
|
"Elaboro ${schemaName}.${tableName}..." | Out-File -FilePath $logFile -Append
|
||||||
|
|
||||||
# Formatta il contenuto
|
# Pulisci e formatta il contenuto
|
||||||
$content = @"
|
$content = $definition.Trim()
|
||||||
$($definition.Trim())
|
# Rimuovi caratteri speciali e di escape HTML
|
||||||
GO
|
$content = $content -replace '
|#x0D;|\r|\n', "`r`n"
|
||||||
"@
|
$content = [System.Web.HttpUtility]::HtmlDecode($content)
|
||||||
|
$content += "`r`nGO"
|
||||||
|
|
||||||
# Rimuovi righe vuote multiple
|
# Rimuovi righe vuote multiple e normalizza i line endings
|
||||||
$lines = $content -split "`r`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
|
$lines = $content -split "\r?\n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
|
||||||
$content = $lines -join "`r`n"
|
$content = $lines -join "`r`n"
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Scrivi il contenuto nel file con codifica UTF8 con BOM
|
# Scrivi il contenuto nel file con codifica UTF8 con BOM
|
||||||
$utf8WithBom = New-Object System.Text.UTF8Encoding($true)
|
[System.IO.File]::WriteAllText($fileName, $content, [System.Text.UTF8Encoding]::new($true))
|
||||||
[System.IO.File]::WriteAllText($fileName, $content, $utf8WithBom)
|
|
||||||
|
|
||||||
Write-Host "Creato file per tabella: ${schemaName}.${tableName}" -ForegroundColor Green
|
Write-Host "Creato file per tabella: ${schemaName}.${tableName}" -ForegroundColor Green
|
||||||
"Creato file per tabella: ${schemaName}.${tableName}" | Out-File -FilePath $logFile -Append
|
"Creato file per tabella: ${schemaName}.${tableName}" | Out-File -FilePath $logFile -Append
|
||||||
|
@ -3,27 +3,12 @@ param(
|
|||||||
[string]$TableName
|
[string]$TableName
|
||||||
)
|
)
|
||||||
|
|
||||||
function Install-RequiredModules {
|
|
||||||
$requiredModule = "SqlServer"
|
|
||||||
|
|
||||||
if (-not (Get-Module -ListAvailable -Name $requiredModule)) {
|
|
||||||
Write-Host "Installazione modulo $requiredModule..."
|
|
||||||
try {
|
|
||||||
Install-Module -Name $requiredModule -Force -AllowClobber -Scope CurrentUser
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
Write-Error "Errore durante l'installazione del modulo $requiredModule. Eseguire PowerShell come amministratore e riprovare."
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Verifica e installa moduli necessari
|
|
||||||
Install-RequiredModules
|
|
||||||
|
|
||||||
# Importa configurazione
|
# Importa configurazione
|
||||||
. "$PSScriptRoot\conf.ps1"
|
. "$PSScriptRoot\conf.ps1"
|
||||||
|
|
||||||
|
# Carica l'assembly System.Data
|
||||||
|
Add-Type -AssemblyName System.Data
|
||||||
|
|
||||||
$InputFile = Join-Path $PSScriptRoot "..\extract\$TableName.csv"
|
$InputFile = Join-Path $PSScriptRoot "..\extract\$TableName.csv"
|
||||||
|
|
||||||
if (-not (Test-Path $InputFile)) {
|
if (-not (Test-Path $InputFile)) {
|
||||||
@ -32,10 +17,7 @@ if (-not (Test-Path $InputFile)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Import SQL Server module if not already loaded
|
|
||||||
if (-not (Get-Module -Name SqlServer)) {
|
|
||||||
Import-Module SqlServer
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host "Lettura dati da: $InputFile"
|
Write-Host "Lettura dati da: $InputFile"
|
||||||
$data = Import-Csv -Path $InputFile -Delimiter ";"
|
$data = Import-Csv -Path $InputFile -Delimiter ";"
|
||||||
@ -79,10 +61,20 @@ try {
|
|||||||
$query = "INSERT INTO $TableName ($columnList) VALUES ($valuesList)"
|
$query = "INSERT INTO $TableName ($columnList) VALUES ($valuesList)"
|
||||||
|
|
||||||
# Execute insert for each row
|
# Execute insert for each row
|
||||||
$connectionString = "Server=$env:dbHostOutput;Database=$env:dbNameOutput;User Id=$env:dbUserOutput;Password=$env:dbPasswordOutput;Encrypt=False"
|
$connectionString = "Server=$env:dbHostOutput;Database=$env:dbNameOutput;User Id=$env:dbUserOutput;Password=$env:dbPasswordOutput;TrustServerCertificate=True"
|
||||||
|
|
||||||
Invoke-Sqlcmd -ConnectionString $connectionString `
|
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
||||||
-Query $query
|
$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
|
||||||
|
|
||||||
|
try {
|
||||||
|
$connection.Open()
|
||||||
|
$command.ExecuteNonQuery() | Out-Null
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
if ($connection.State -eq 'Open') {
|
||||||
|
$connection.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host "Dati importati con successo nella tabella: $TableName"
|
Write-Host "Dati importati con successo nella tabella: $TableName"
|
||||||
|
Loading…
x
Reference in New Issue
Block a user