Skip to content

Commit db3e52a

Browse files
author
Calvin Tapp
committed
PowerShellFunctinos Initial
1 parent 4f7dfd9 commit db3e52a

13 files changed

+379
-0
lines changed

CommonFunctions/CommonFunctions.psd1

7.9 KB
Binary file not shown.

CommonFunctions/CommonFunctions.psm1

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#Define import directory
2+
$Public = @(Get-ChildItem $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue)
3+
4+
#dot source all the files
5+
foreach ($import in $Public) {
6+
try {
7+
.$import.fullname
8+
}
9+
catch {
10+
Write-Error -Message "Failed to import $($import.fullname): $_"
11+
}
12+
}
13+
14+
Export-ModuleMember -Function $Public.BaseName

CommonFunctions/GenerateModule.ps1

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
$root = Split-Path $PSCommandPath -Parent
2+
$ModuleName = "CommonFunctions"
3+
$Author = "Tappau"
4+
$Description = "Powershell module of helpful tasks, I've required at somepoint"
5+
6+
#Create the module and related files
7+
New-ModuleManifest -Path $root\$ModuleName.psd1 `
8+
-RootModule $root\$ModuleName.psm1 `
9+
-Description $Description `
10+
-powershellVersion 4.0 `
11+
-Author $Author `
12+
-ModuleVersion '1.0' `
13+
-ProjectUri "http://github.com/Tappau/PowerShellFunctions"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function Convert-SecureStringToPlainText {
2+
param (
3+
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
4+
[System.Security.SecureString]$SecurePassword
5+
)
6+
7+
try {
8+
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
9+
$plaintext = [Runtime.InteropServices.Marshal]::PtrToStringAuto($pointer)
10+
return $plaintext
11+
}
12+
finally {
13+
#release pointer
14+
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer)
15+
}
16+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function Convert-ToUnc {
2+
param (
3+
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
4+
[string]$Path,
5+
[Parameter(Mandatory = $true)]
6+
[ValidateScript( {
7+
if (Test-Connection -ComputerName $_ -Quiet -Count 1) {
8+
$true
9+
}
10+
else {
11+
throw "The computer $($_) is not available"
12+
}
13+
})]
14+
[string] $ComputerName
15+
)
16+
17+
$Drive = (Split-Path $Path -Qualifier).Split(":")[0]
18+
return Join-Path -Path "\\" -ChildPath (Join-Path -Path $ComputerName -ChildPath (Join-Path -Path "$Drive$" -ChildPath (Split-Path -Path $Path -NoQualifier)))
19+
}
20+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function Get-ComputerInformation {
2+
[CmdletBinding()]
3+
param (
4+
$ComputerName
5+
)
6+
7+
process {
8+
#Computer System
9+
$ComputerSystem = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName
10+
# Operating System
11+
$OperatingSystem = Get-WmiObject -Class Win332_OperatingSystem -ComputerName $ComputerName
12+
#BIOS
13+
$Bios = Get-WmiObject -Class Win32_BIOS -ComputerName $ComputerName
14+
15+
##Prepare some output
16+
$Properties = @{
17+
ComputerName = $ComputerName
18+
Manufacturer = $ComputerSystem.Manufacturer
19+
Model = $ComputerSystem.Model
20+
OperatingSystem = $OperatingSystem.Caption
21+
OpertingSystemVersion = $OperatingSystem.Version
22+
SerialNumber = $Bios.SerialNumber
23+
}
24+
25+
##Output results
26+
New-Object -typename PSobject -property $Propertiess
27+
}
28+
}
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function Get-MsBuild {
2+
param (
3+
[int] $MaxVersion = 2017
4+
)
5+
6+
$2017BuildTools = "$Env:programfiles (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild.exe"
7+
$2017Enterprise = "$Env:programfiles (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\msbuild.exe"
8+
$2017Professional = "$Env:programfiles (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\msbuild.exe"
9+
$2017Community = "$Env:programfiles (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild.exe"
10+
$fallback2015Path = "${Env:ProgramFiles(x86)}\MSBuild\14.0\Bin\MSBuild.exe"
11+
$fallback2013Path = "${Env:ProgramFiles(x86)}\MSBuild\12.0\Bin\MSBuild.exe"
12+
$fallbackPath = "C:\Windows\Microsoft.NET\Framework\v4.0.30319"
13+
14+
If ((2017 -le $MaxVersion) -And (Test-Path $2017BuildTools)) { return $2017BuildTools }
15+
If ((2017 -le $MaxVersion) -And (Test-Path $2017Enterprise)) { return $2017Enterprise }
16+
If ((2017 -le $MaxVersion) -And (Test-Path $2017Professional)) { return $2017Professional }
17+
If ((2017 -le $MaxVersion) -And (Test-Path $2017Community)) { return $2017Community }
18+
If ((2015 -le $MaxVersion) -And (Test-Path $fallback2015Path)) { return $fallback2015Path }
19+
If ((2013 -le $MaxVersion) -And (Test-Path $fallback2013Path)) { return $fallback2013Path }
20+
If (Test-Path $fallbackPath) { return $fallbackPath }
21+
22+
throw "Unable to find msbuild"
23+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function Get-SqlPackage {
2+
param (
3+
4+
)
5+
$DefaultSqlInstallDir = "C:\Program Files (x86)\Microsoft SQL Server"
6+
7+
if (-not(Test-Path $DefaultSqlInstallDir)) {
8+
throw [System.IO.DirectoryNotFoundException] "$DefaultSqlInstallDir not found."
9+
}
10+
$exe = (Get-ChildItem $DefaultSqlInstallDir -Include "sqlpackage.exe" -Recurse).FullName
11+
12+
if ($exe.Count -gt 1) {
13+
return $exe[$exe.Count - 1] ##Return last match in array.
14+
}elseif ($exe.Count -le 0) {
15+
throw "SqlPackage.exe not found"
16+
}
17+
else {
18+
return $exe
19+
}
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<#
2+
.SYNOPSIS
3+
Collection of functions that can be used for various usages.
4+
#>
5+
function Get-UserSetVariables {
6+
get-variable | where-object {(@(
7+
"FormatEnumerationLimit",
8+
"MaximumAliasCount",
9+
"MaximumDriveCount",
10+
"MaximumErrorCount",
11+
"MaximumFunctionCount",
12+
"MaximumVariableCount",
13+
"PGHome",
14+
"PGSE",
15+
"PGUICulture",
16+
"PGVersionTable",
17+
"PROFILE",
18+
"PSSessionOption"
19+
) -notcontains $_.name) -and `
20+
(([psobject].Assembly.GetType('System.Management.Automation.SpecialVariables').GetFields('NonPublic,Static')`
21+
| Where-Object FieldType -eq ([string])`
22+
| ForEach-Object GetValue $null)) -notcontains $_.name
23+
}
24+
}

CommonFunctions/Public/Invoke-Sql.ps1

+150
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
<#
2+
.SYNOPSIS
3+
Execute provided SQL against provided Server Instance accepts parameters
4+
.DESCRIPTION
5+
Will execute SQL against instance, If UserName and password are not provided then integrated security is used.
6+
if TargetDatabase not provided then query should contain fully qualified paths for query.
7+
.PARAMETER ServerInstance
8+
Name of instance to execute against
9+
.PARAMETER Query
10+
String Query to run
11+
.PARAMETER Parameters
12+
Dictionary of parameter names and values.
13+
.PARAMETER TargetDatabase
14+
If Provided will define 'Initial Catalog' parameter on connection string
15+
.PARAMETER NonQuery
16+
States that this query does not return results i.e. Action Queries (CREATE, ALTER, DROP, INSERT, UPDATE, DELETE)
17+
.PARAMETER UserName
18+
User to execute as
19+
.PARAMETER Password
20+
SecureString password to utilise
21+
.EXAMPLE
22+
Invoke-Sql -ServerInstance localhost\sqlexpress -Query "SELECT * FROM Person"
23+
Will execute and return object of results
24+
.EXAMPLE
25+
Invoke-Sql -ServerInstance localhost\sqlexpress -Query "SELECT FirstName, LastName FROM Person WHERE FirstName=@fname" -Parameters @{fname = 'John'}
26+
Will execute the query and return object of the results
27+
.EXAMPLE
28+
Invoke-Sql -ServerInstance localhost\sqlexpress -Query "INSERT INTO Person(FirstName, LastName) VALUES('Jane', 'Doe')" -NonQuery
29+
Will execute returning if number of rows affected.
30+
.EXAMPLE
31+
Invoke-Sql -ServerInstance localhost\sqlexpress -Query "INSERT INTO Person(FirstName, LastName) VALUES(@fname, @lname)" -Parameter @{fname='Jane'; lname='Doe'} -NonQuery
32+
Will execute returning if number of rows affected.
33+
.NOTES
34+
Only executable against Microsoft SQL Server instances.
35+
#>
36+
function Invoke-Sql {
37+
[CmdletBinding()]
38+
param (
39+
[parameter(Mandatory = $true)]
40+
[String] $ServerInstance,
41+
42+
[parameter(Mandatory = $true)]
43+
[string] $Query,
44+
45+
[parameter(Mandatory = $false)]
46+
[hashtable]$Parameters,
47+
48+
[parameter(Mandatory = $false)]
49+
[string] $TargetDatabase,
50+
51+
[parameter(Mandatory = $false)]
52+
[switch] $NonQuery,
53+
54+
[parameter(HelpMessage = "UserName to use")]
55+
[string]$UserName,
56+
57+
[parameter(Mandatory = $false)]
58+
[securestring]$Password
59+
)
60+
61+
begin {
62+
$connectionString = "Data Source=$ServerInstance;"
63+
if ($TargetDatabase) {
64+
$connectionString += "Initial Catalog=$TargetDatabase;"
65+
}
66+
67+
$conn = New-Object system.data.SqlClient.sqlconnection
68+
if ($UserName -and $Password) {
69+
Write-Verbose "Using specified credentials"
70+
$creds = New-Object System.Data.SqlClient.SqlCredential($UserName, $Password)
71+
}
72+
else {
73+
$connectionString += "Integrated Security = True;"
74+
}
75+
76+
$conn.ConnectionString = $connectionString
77+
if ($null -ne $creds) {
78+
$conn.Credential = $creds
79+
}
80+
}
81+
82+
process {
83+
try {
84+
if ($NonQuery) {
85+
#Execute as NonQuery
86+
Write-verbose "Creating SQL Command..."
87+
$cmd = New-Object system.data.SqlClient.SqlCommand($Query, $conn)
88+
if ($Parameters.Count -gt 0) {
89+
$cmd.Parameters.Clear()
90+
foreach ($p in $Parameters.Keys) {
91+
[void] $cmd.Parameters.AddWithValue("@$p", $Parameters[$p])
92+
}
93+
}
94+
Write-Verbose "Opening SQL Connection..."
95+
$conn.Open()
96+
Write-Verbose "Executing SQL Command..."
97+
Write-Verbose $cmd.CommandText
98+
$result = $cmd.ExecuteNonQuery()
99+
if ($result -gt 0) {
100+
Write-Verbose "Successfully Executed Command"
101+
return $result
102+
}
103+
else {
104+
Write-Error $Error
105+
}
106+
}
107+
else {
108+
#then execute as required returning object of results
109+
$cmd = New-Object system.data.SqlClient.SqlCommand($Query, $conn)
110+
if ($Parameters.Count -gt 0) {
111+
$cmd.Parameters.Clear()
112+
foreach ($p in $Parameters.Keys) {
113+
[void] $cmd.Parameters.AddWithValue("@$p", $Parameters[$p])
114+
}
115+
}
116+
Write-Verbose "Opening SQL Connection..."
117+
$conn.Open()
118+
Write-Verbose $cmd.CommandText
119+
$reader = $cmd.ExecuteReader() | Out-Null
120+
$results = @()
121+
while ($reader.Read()) {
122+
$row = @{}
123+
for ($i = 0; $i -lt $reader.FieldCount; $i++) {
124+
Write-Verbose "Adding $($reader.GetName($i)) to psobject"
125+
$row[$reader.GetName($i)] = $reader.GetValue($i)
126+
}
127+
$results += New-Object psobject -Property $row
128+
}
129+
$conn.Close()
130+
return $results
131+
}
132+
}
133+
catch [system.data.SqlClient.sqlexception] {
134+
Write-Error "One or more of the rows being affected were locked. Please check your query and data then try again."
135+
}
136+
catch {
137+
Write-Error "An error occurred while attempting to open the database connection and execute a command"
138+
}
139+
finally {
140+
if ($conn.State -eq 'Open') {
141+
Write-Verbose "Closing connection..."
142+
$conn.Close()
143+
}
144+
}
145+
}
146+
147+
end {
148+
$conn.Dispose()
149+
}
150+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<#
2+
.SYNOPSIS
3+
Will display a prompt until a y/n response is provided.
4+
.DESCRIPTION
5+
Will prompt user for confirmation expecting y/n answer and returning that as a boolean
6+
.PARAMETER Message
7+
The text that should be shown will be appended with (Y/N) ?
8+
.EXAMPLE
9+
Show-ConfirmationPrompt "Do you wish to continue"
10+
Will display as Do you wich to contine (Y/N) ?
11+
returns $true if Y/y otherwise $false
12+
#>
13+
function Show-ConfirmationPrompt {
14+
param (
15+
[string]$Message
16+
)
17+
do {
18+
$reply = Read-Host -Prompt ($Message + " (Y/N) ?")
19+
} until ("y","Y","n","N" -contains $reply)
20+
return ("y", "Y" -contains $reply)
21+
}
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<#
2+
.SYNOPSIS
3+
Test if a path is UNC
4+
.DESCRIPTION
5+
Will return true if Path begins with \\
6+
.PARAMETER Path
7+
Path of that is subject of test
8+
.EXAMPLE
9+
Test-UncPath -Path "C:\Windows"
10+
Will return false as not a UNC Path
11+
.EXAMPLE
12+
Test-UncPath -Path "\\localhost\C$\Windows"
13+
Will return true as not a UNC Path
14+
#>
15+
function Test-UncPath {
16+
param (
17+
[Parameter(Mandatory=$true)]
18+
$Path
19+
)
20+
if($Path.StartsWith("\\")){ return $true } else { return $false }
21+
}

0 commit comments

Comments
 (0)