‎12-02-2021 11:46 AM
‎12-02-2021 11:46 PM
## Modules needed to run this code
install-module sqlserver -AllowClobber -Force
Import-Module sqlserver
Install-Module ImportExcel
### Connects the SQL DB
Set-Location SQLSERVER:\sql\SQLSERVERNAME\INSTANACENAME\databases\DBNAME
### assuming the headers are column1 and column2
$excelAssets = Import-Excel C:\temp\info.xslx
foreach($row in $excelAssets ){
$field1 = "'" + $row.column1 + "'"
$field2 = "'" + $row.column2 + "'"
$sqlQuery = "INSERT INTO tblAssetRelations (ParentAssetID, ChildAssetID, Type)
VALUES (
(SELECT tblAssets.AssetID FROM tblAssets WHERE tblAssets.AssetName = $field2),
(SELECT tblAssets.AssetID FROM tblAssets WHERE tblAssets.AssetName = $field1),
12
);"
Invoke-Sqlcmd -Query $sqlQuery
}
‎12-02-2021 09:47 PM
function RunMSSQLQuery {
param(
[Parameter(Mandatory = $true)][String] $mssql_server_instance,
[Parameter(Mandatory = $true)][String] $mssql_databasename,
[Parameter(Mandatory = $true)][String] $mssql_query
)
$dbquery = $mssql_query
#Delcare Connection Variables
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
#$connectionTemplate = "Data Source={0};Integrated Security=false;Initial Catalog={1};User ID=$ms_uid;Password =$ms_pwd;"
$connectionString = [string]::Format($connectionTemplate, $mssql_server_instance, $mssql_databasename)
#Establish connection to SQL server
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
#Execute database query command
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $dbquery
$command.Connection = $connection
$command.CommandTimeout = 0
#Load up the Tables in a dataset
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$EXECUTE_QUERY = $SqlAdapter.Fill($DataSet)
$connection.Close()
if ($EXECUTE_QUERY)
{
Write-Host `n"Query executed: "$dbquery
}
return $dbquery
}
Experience Lansweeper with your own data. Sign up now for a 14-day free trial.
Try Now