PowerShell Code Snippet

Strip-Word

 Function Strip-Word { 
    Param ( 
        [Parameter(mandatory=$true,Position=1)][string]$word, 
        [Parameter(mandatory=$true,Position=2)][int]$length, 
        [Parameter(mandatory=$false,Position=3)][AllowNull()][switch]$encode 
    )
    
    $word = $word -replace '[^a-zA-Z0-9-\(\)_ ]', ''

    if($encode) { 
        return [System.Web.HttpUtility]::UrlEncode($word.PadRight($length,' ').Substring(0,$length).Trim());
    } else { 
        return $word.PadRight($length,' ').Substring(0,$length).Trim(); 
    }
} 

Filter-UnwantedCharacters

 Function Filter-UnwantedCharacters(
    [string]$Word, 
    [string]$Pattern = '[^a-zA-Z0-9]'
) { 
    return $Word -replace $Pattern, '' 
} 

Combine-Objects

 Function Combine-Objects {
    Param ( 
        [Parameter(mandatory=$true)][AllowNull()]$Object1, 
        [Parameter(mandatory=$true)][AllowNull()] $Object2 
    )    
    $arguments = [Pscustomobject]@{}
    if($Object1 -ne $null) { 
        ForEach ($p in ($Object1 | Get-Member -MemberType NoteProperty)) { 
            Add-Member -InputObject $arguments -MemberType NoteProperty -Name "$($p.Name)" -Value $Object1."$($p.Name)" -Force 
        } 
    }
    if($Object1 -ne $null) { 
        ForEach ($p in ($Object2 | Get-Member -MemberType NoteProperty)) { 
            Add-Member -InputObject $arguments -MemberType NoteProperty -Name "$($p.Name)" -Value $Object2."$($p.Name)" -Force 
        } 
    }
    $Object3 = [Pscustomobject]$arguments
    return $Object3
} 

Split-Array to Multi-Array

Function Split-Array {
<#  
  .SYNOPSIS   
    Split an array
  .NOTES
    Version : July 2, 2017 - implemented suggestions from ShadowSHarmon for performance   
  .PARAMETER inArray
   A one dimensional array you want to split
  .EXAMPLE  
   Split-Array -inArray @(1,2,3,4,5,6,7,8,9,10) -parts 3
  .EXAMPLE  
   Split-Array -inArray @(1,2,3,4,5,6,7,8,9,10) -size 3
#> 
    param(
        $inArray,
        [int]$parts,
        [int]$size
    )
    if ($parts) { 
        $PartSize = [Math]::Ceiling($inArray.count / $parts); 
    } 
    if ($size) { 
        $PartSize = $size; $parts = [Math]::Ceiling($inArray.count / $size); 
    }
    $outArray = New-Object 'System.Collections.Generic.List[psobject]';
    for ($i=1; $i -le $parts; $i++) { 
        $start = (($i-1)*$PartSize); 
        $end = (($i)*$PartSize) - 1; 
    
        if ($end -ge $inArray.count) {
            $end = $inArray.count -1;
        }; 
    
        $outArray.Add(@($inArray[$start..$end]));
    }
    return ,$outArray;
} 

Get-FileName

Function Get-FileName($initialDirectory) {   
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

    $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
    $SaveFileDialog.initialDirectory = $initialDirectory
    $SaveFileDialog.filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*”
    $SaveFileDialog.ShowDialog() | Out-Null
    $SaveFileDialog.filename
}
 

ConvertTo-JsonifiablePSObject

Function ConvertTo-JsonifiablePSObject
{
    param
    (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [PSObject]$Object
    )
    $newObjectProperties = @{}
    foreach ($property in ($Object.psobject.properties | Sort-Object -Property "Name"))
    {
        $value = $property.Value
        if ($property.TypeNameOfValue -eq "System.Management.Automation.PSCustomObject") {
            $value = ConvertTo-JsonifiablePSObject -Object $property.Value
        } elseif ($property.TypeNameOfValue -eq "System.DateTime") {
            $value = $property.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK")
        }
        $newObjectProperties[$property.Name] = $value
    }
    return New-Object -TypeName PSObject -Property $newObjectProperties
} 

Save-Jpeg

Function Save-Jpeg (
    [string]$imagePath, 
    [string]$imageOutPut,
    $quality = $(if ($quality -lt 0 -or  $quality -gt 100){throw( "quality must be between 0 and 100.")})
) { 
    [void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    $bmp = New-Object System.Drawing.Bitmap $imagePath
    
    #Encoder parameter for image quality 
    $myEncoder = [System.Drawing.Imaging.Encoder]::Quality
    $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1) 
    $encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($myEncoder, $quality)
    
    # get codec
    $myImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|where {$_.MimeType -eq 'image/jpeg'}
    
    #save to file
    $bmp.Save($imageOutPut,$myImageCodecInfo, $($encoderParams))
}

Get-DatabaseData

Function Get-DatabaseData {
[CmdletBinding()]
param (
	[string]$connectionString,
	[string]$query,
	[switch]$isSQLServer,
	[switch]$disableTimeOut
)
	#Write-Host $connectionString,$query,$isSQLServer
	if ($isSQLServer) {
		Write-Verbose 'in SQL Server mode'
		$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
	} else {
		Write-Verbose 'in OleDB mode'
		$connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
    }

    $connection.ConnectionString = $connectionString
    $command = $connection.CreateCommand()
    $command.CommandText = $query
	if($disableTimeOut -eq $true){ $command.CommandTimeout = 0 }

    if ($isSQLServer) {
		$adapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $command
	} else {
		$adapter = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter $command
	}


    $dataset = New-Object -TypeName System.Data.DataSet
    $adapter.Fill($dataset) | Out-Null
    return $dataset.Tables[0]
}

Invoke-DatabaseQuery

Function Invoke-DatabaseQuery {
[CmdletBinding()]
param (
	[string]$connectionString,
	[string]$query,
	[switch]$isSQLServer
)

	if ($isSQLServer) {
		Write-Verbose 'in SQL Server mode'
		$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
    } else {
		Write-Verbose 'in OleDB mode'
		$connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
	}
	
    $connection.ConnectionString = $connectionString
    $command = $connection.CreateCommand()
    $command.CommandText = $query
    $connection.Open()
    $temp = $command.ExecuteNonQuery()
    $connection.close()
} 

Send-EmailToOffice356

Function Send-EmailToOffice356 {
[CmdletBinding()]
param
(
	[Parameter(Mandatory=$true)]
	[string] $fromTitle,
	[Parameter(Mandatory=$true)]
	[string] $fromAddress,
	[Parameter(Mandatory=$true)]
	[string] $password,
	[Parameter(Mandatory=$true)]
	[string] $toAddress,
	[Parameter(Mandatory=$true)]
	[string] $subject,
	[Parameter(Mandatory=$true)]
	[string] $message,
	[Parameter(Mandatory=$false)]
	[string] $SmtpServer = "smtp.office365.com",
	[Parameter(Mandatory=$false)]
	[string] $SmtpServerPort = "587",
	[Parameter(Mandatory=$false)]
	[String[]] $attachmennts = $null,
	[Parameter(Mandatory=$false)]
	[string] $replyAddress = $null
)

	$emailSmtpServer = "$SmtpServer"
	$emailSmtpServerPort = "$SmtpServerPort"
	$emailSmtpUser = "$fromAddress"
	$emailSmtpPass = "$password"
	$emailFrom = "$fromTitle <$fromAddress>"
	$emailTo = $toAddress
			
	$emailMessage = New-Object System.Net.Mail.MailMessage( $emailFrom , $emailTo )
	$emailMessage.ReplyToList = New-Object System.Net.Mail.MailAddressCollection;
	if( $replyAddress -ne $null ) {
		$emailMessage.ReplyToList.Add("$replyAddress");
	}
	$emailMessage.Subject = "$subject"
	$emailMessage.IsBodyHtml = $true
	$emailMessage.Body = $message
	if( $attachmennts -ne $null ){
		foreach($attachmennt in $attachmennts){ 
			$emailMessage.Attachments.Add($attachmennt)	
		}
	}
	
	try {
		$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort ) 
		$SMTPClient.EnableSsl = $true
		$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass ); 
		$SMTPClient.Send( $emailMessage )
		return $true;
	}
	catch {
		return $false;
	}
	
	return $false;
}

Get-RandomPassword

Function Get-RandomPassword 
{
	[CmdletBinding()]
	param
	(
		[int]
		$length = 10,
		[String]
		$characters = 'abcdefghkmnprstuvwxyzABCDEFGHKLMNPRSTUVWXYZ123456789'
	)
	
	# select random characters
	$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }

	# output random pwd
	$private:ofs=""
	[String]$characters[$random]
}

Coalesce

# http://stackoverflow.com/questions/10623907/null-coalescing-in-powershell
Function Coalesce([string] $a, [string] $b) { 
    if (($a -ne $null) -and ("$($a)".Trim().Length -ge 1)) { $a } 
    elseif (($b -ne $null) -and ("$($b)".Trim().Length -ge 1)) { $b }
    else { $null }
}
#$s = Coalesce $myval "new value"
New-Alias "??" Coalesce
#$s = ?? $myval "new value"

Function IfNull($a, $b, $c) { 
	if ($a -eq $null -or ("$($a)".Trim().Length -eq 0)) { $b } 
	else { $c } 
}
#$s = IfNull $myval "new value" $myval
#$x = IfNull $myval "" $otherval

Function IfTrue($a, $b, $c) { 
	if ($a-and ("$($a)".Trim().Length -ge 1)) { $b } 
	else { $c } 
}
#$x = IfTrue ($myval -eq $null) "" $otherval
New-Alias "?:" IfTrue
#$ans = ?: ($q -eq "meaning of life") 42 $otherval

Encrypt/Decrypt-String

[Reflection.Assembly]::LoadWithPartialName("System.Security")

Function Encrypt-String(
	$String, 
	$Passphrase, 
	$salt="P@ssw0rd", 
	$init="Yet another key", 
	[switch]$arrayOutput
){
   $r = new-Object System.Security.Cryptography.RijndaelManaged
   $pass = [Text.Encoding]::UTF8.GetBytes($Passphrase)
   $salt = [Text.Encoding]::UTF8.GetBytes($salt)

   $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
   $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]
   
   $c = $r.CreateEncryptor()
   $ms = new-Object IO.MemoryStream
   $cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write"
   $sw = new-Object IO.StreamWriter $cs
   $sw.Write($String)
   $sw.Close()
   $cs.Close()
   $ms.Close()
   $r.Clear()
   [byte[]]$result = $ms.ToArray()
   if($arrayOutput) { return $result } 
   else { return [Convert]::ToBase64String($result) }
}

Function Decrypt-String(
	$Encrypted, 
	$Passphrase, 
	$salt="P@ssw0rd", 
	$init="Yet another key"
) {
   if($Encrypted -is [string]){
      $Encrypted = [Convert]::FromBase64String($Encrypted)
   }

   $r = new-Object System.Security.Cryptography.RijndaelManaged
   $pass = [System.Text.Encoding]::UTF8.GetBytes($Passphrase)
   $salt = [System.Text.Encoding]::UTF8.GetBytes($salt)

   $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
   $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]

   $d = $r.CreateDecryptor()
   $ms = new-Object IO.MemoryStream @(,$Encrypted)
   $cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read"
   $sr = new-Object IO.StreamReader $cs
   Write-Output $sr.ReadToEnd()
   $sr.Close()
   $cs.Close()
   $ms.Close()
   $r.Clear()
}