I’m part of a company with a lot of Powershell newbies (myself one of them). I understand it a little better than most, and I’m trying to create a function where users can be prompted for input that would, by the function’s end, spit out a text file with an Invoke-SQLCmd for them to run with verbose output. I’m doing this as a teaching/learning experience for the end users who are overwhelmed at the thought of Powershell. Here’s a script I use without issue:
[CmdletBinding()]Param(
[Parameter(Mandatory = $True, HelpMessage = “Enter one or more filepath(s) in double quotes”)]
[string]$paths)
Enter a path for the text file output you require (Ex. C:\Temp\Output.txt)
$OutputPath = Read-Host “Enter path for text file output here (Format - DriveLetter:\Filepath\File.txt)”
Create a variable for these values to live in
$Output =
Create a foreach loop to prompt the user for Server Instance and database, then…
foreach ($path in $paths){
$ServerInstance=Read-Host"Enter Server Instance for $path (full FQDN if applicable)"
$Database=Read-Host"Enter Database for $path"
…write the output in the format of the desired command
Write-Output"Invoke-SQLCMD -ServerInstance $ServerInstance -Database $Database -InputFile $Path -Verbose"}
Save the text file to your machine.
$Output | Out-File $OutputPath
Here’s my attempt at converting this into a function with some validation:
function Convert-SQLtoPS1{[CmdletBinding()]
param(
[Parameter(Mandatory = $True, HelpMessage = “Enter one or more filepath(s) in double quotes (Ex. \Server\Directory\SubDirectory\SQL\SqlScript.sql”)]
[string]$ScriptPath,
[ValidateScript({Test-Path $ScriptPath})]
[Parameter(Mandatory = $True, HelpMessage = “Enter path for text file output here (Format - DriveLetter:\Filepath\File.txt)”)]
[string]$OutputPath,
[Parameter(Mandatory=$True, HelpMessage = “Enter Server Instance (FQDN required if applicable)”)]
[string]$Instance,
[ValidateScript({Test-Netconnection $Instance -InformationLevel Quiet})]
[Parameter(Mandatory=$True, HelpMessage = “Enter Database”)]
[string]$Database,
[ValidateScript({Get-SqlInstance -ServerInstance $Instance | Get-SQLDatabase $Database})]
)
$Output=Write-Output"Invoke-SQLCMD -ServerInstance $ServerInstance -Database $Database -InputFile $Path -Verbose"
} $Output | Out-File $OutputPath