PortValhalla/scripts/Common/Scripts/Scripting.ps1

71 lines
2 KiB
PowerShell

<#
.SYNOPSIS
Converts the specified value into a form to safle inject it into a script.
.PARAMETER value
The value to convert for injection.
#>
function ConvertTo-Injection {
param(
$Value
)
"([System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String('$(
[System.Convert]::ToBase64String([System.Text.Encoding]::Default.GetBytes($value))
)')))"
}
<#
.SYNOPSIS
Writes a PowerShell script to a specified location.
.PARAMETER FileName
The name of the file to write the script to.
.PARAMETER Script
The script to write to the file.
.PARAMETER Replace
A value indicating whether the file should be overwritten if it exists.
.PARAMETER Append
A value indicating whether the content should be appended if the file already exists.
#>
function Write-PSScript {
param(
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName="Common")]
[Parameter(ParameterSetName="Replace")]
[Parameter(ParameterSetName="Append")]
[string] $FileName,
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName="Common")]
[Parameter(ParameterSetName="Replace")]
[Parameter(ParameterSetName="Append")]
[string] $Script,
[Parameter(ParameterSetName="Replace", Mandatory=$true)]
[switch] $Replace,
[Parameter(ParameterSetName="Append", Mandatory=$true)]
[switch] $Append
)
Import-Module PSScriptAnalyzer;
$dirName = Split-Path -Parent $FileName;
$content = Invoke-Formatter -ScriptDefinition $Script;
$exists = Test-Path -PathType Leaf $FileName;
if (-not (Test-Path -PathType Container $dirName)) {
$null = New-Item -ItemType Directory $dirName;
}
if ($exists -and ($Append.IsPresent)) {
Add-Content -Force $FileName "`n$content";
} else {
if ((-not $exists) -or $Replace.IsPresent) {
Set-Content -Force $FileName $content;
} else {
Write-Host "The file ``$FileName`` already exists!";
}
}
}