Skip to main content

Demonstrates how to specify and use SQL Server parameters in the SqlServer PowerShell module.

# Import the SqlServer module
Import-Module SqlServer

# Define the SQL query with parameters
$sqlQuery = @'
SELECT *
FROM YourTable
WHERE Column1 = @Param1 AND Column2 = @Param2 AND DateColumn = @DateParam
'@

# Define the date format for SQL
$sqlDateTimeFormat = 'yyyy-MM-dd HH:mm:ss'

# Get the current date and time
$now = (Get-Date -Format $sqlDateTimeFormat)

# Define the parameters
$parameters = @{
    Param1 = 'Value1'
    Param2 = 'Value2'
    DateParam = [datetime]::Parse($now)
}

# Execute the SQL query with parameters
$result = Invoke-Sqlcmd -Query $sqlQuery -Variable $parameters -ServerInstance 'YourServerInstance' -Database 'YourDatabase' -As DataRow

# Loop through the result set
foreach ($row in $result)
{
    Write-Output "Column1: $($row.Column1), Column2: $($row.Column2), DateColumn: $($row.DateColumn)"
}