Author : HASSAN MD TAREQ | Updated : 2021/09/25
Get Current Script Directory
$ScriptPath = ""
if ($psISE) { # If using ISE
$ScriptPath = Split-Path -Parent $psISE.CurrentFile.FullPath
} elseif($PSVersionTable.PSVersion.Major -gt 3) { # If Using PowerShell 3 or greater
$ScriptPath = $PSScriptRoot
} else { # If using PowerShell 2 or lower
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Path
}
echo $ScriptPath
StackOverflow question: https://stackoverflow.com/questions/5466329/whats-the-best-way-to-determine-the-location-of-the-current-powershell-script
Keep Shell Window Open After Running Script
$xyz = ""
# ... ... ...
echo $xyz
#
# Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
#
Read-Host -Prompt "Press Enter to exit"
StackOverflow answer: https://stackoverflow.com/a/24620771/4802664
Test SQL Server Connetion
#
# Collected from: https://mcpmag.com/articles/2018/12/10/test-sql-connection-with-powershell.aspx
#
function Test-SqlConnection {
param(
[Parameter(Mandatory)]
[string]$ServerName,
[Parameter(Mandatory)]
[string]$DatabaseName,
[Parameter(Mandatory)]
[pscredential]$Credential
)
$ErrorActionPreference = 'Stop'
try {
$userName = $Credential.UserName
$password = $Credential.GetNetworkCredential().Password
$connectionString = 'Data Source={0};database={1};User ID={2};Password={3}' -f $ServerName,$DatabaseName,$userName,$password
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString
$sqlConnection.Open()
## This will run if the Open() method does not throw an exception
$true
} catch {
$false
} finally {
## Close the connection when we're done
$sqlConnection.Close()
}
}
#
# Get server instance (Computer\Instance), run follwoing command in SSMS
# SELECT @@servername + '\' + @@servicename
# Get server name only: SELECT @@servername
#
Test-SqlConnection -ServerName 'SqlServerName' -DatabaseName 'AdventureWorksLT2019' -Credential (Get-Credential)