PortValhalla/scripts/lib/Scripting.ps1

74 lines
2.2 KiB
PowerShell
Raw Normal View History

<#
.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))
)')))"
}
2024-08-07 18:30:12 +00:00
<#
.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(
2024-10-06 19:25:34 +00:00
[Parameter(Mandatory = $true)]
[Parameter(ParameterSetName = "Common")]
[Parameter(ParameterSetName = "Replace")]
[Parameter(ParameterSetName = "Append")]
2024-08-07 18:30:12 +00:00
[string] $FileName,
2024-10-06 19:25:34 +00:00
[Parameter(Mandatory = $true)]
[Parameter(ParameterSetName = "Common")]
[Parameter(ParameterSetName = "Replace")]
[Parameter(ParameterSetName = "Append")]
[string] $Script,
2024-10-06 19:25:34 +00:00
[Parameter(ParameterSetName = "Replace", Mandatory = $true)]
[switch] $Replace,
2024-10-06 19:25:34 +00:00
[Parameter(ParameterSetName = "Append", Mandatory = $true)]
2024-08-07 18:30:12 +00:00
[switch] $Append
)
Import-Module PSScriptAnalyzer;
$dirName = Split-Path -Parent $FileName;
$Script = ($Script -split "\r?\n") -join [System.Environment]::NewLine;
2024-08-07 18:30:12 +00:00
$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";
2024-10-06 19:25:34 +00:00
}
else {
2024-08-07 18:30:12 +00:00
if ((-not $exists) -or $Replace.IsPresent) {
Set-Content -Force $FileName $content;
2024-10-06 19:25:34 +00:00
}
else {
2024-08-07 18:30:12 +00:00
Write-Host "The file ``$FileName`` already exists!";
}
}
}