functions/common/Convert-NavToolToSilentScript.ps1

function Convert-NavToolToSilentScript {
    <#
    .SYNOPSIS
    Comments out Write-Host and Get-Command -Module lines in a NAV tool script to silence output.
 
    .DESCRIPTION
    This function reads a PowerShell script (e.g., NavAdminTool.ps1), comments out all lines starting with Write-Host
    and Get-Command -Module, and removes the digital signature block (if present). The modified file can be saved in place
    or as a separate file using the -OutputPath parameter.
 
    .PARAMETER InputPath
    Path to the input PowerShell script file to be processed.
 
    .PARAMETER InPlace
    If specified, the original file will be modified in-place. Otherwise, a new file will be created.
 
    .PARAMETER OutputPath
    Optional path to save the modified script. Ignored if -InPlace is used.
 
    .OUTPUTS
    FileInfo object for the modified file.
 
    .EXAMPLE
    Convert-NavToolToSilentScript -InputPath "C:\Tools\NavAdminTool.ps1" -InPlace
 
    .EXAMPLE
    Convert-NavToolToSilentScript -InputPath "C:\Tools\NavAdminTool.ps1" -OutputPath "C:\Tools\NavAdminTool_Silent.ps1"
 
    .NOTES
    The function removes the digital signature block to prevent signature errors when ExecutionPolicy is RemoteSigned.
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$InputPath,

        [switch]$InPlace,

        [string]$OutputPath
    )

    if (-not (Test-Path $InputPath)) {
        throw "File '$InputPath' was not found."
    }

    if (-not $InPlace -and -not $OutputPath) {
        $OutputPath = [System.IO.Path]::Combine(
            [System.IO.Path]::GetDirectoryName($InputPath),
            "$([System.IO.Path]::GetFileNameWithoutExtension($InputPath))_Silent.ps1"
        )
    }

    $targetPath = if ($InPlace) { $InputPath } else { $OutputPath }

    $lines = Get-Content -Path $InputPath -Encoding UTF8 -ErrorAction Stop -Force

    $modifiedLines = foreach ($line in $lines) {
        if ($line -match '^\s*# SIG # Begin signature block') {
            break
        }
        elseif ([string]::IsNullOrWhiteSpace($line)) {
            continue
        }
        elseif ($line -match '^\s*Write-Host\b' -or $line -match '^\s*Get-Command\s+-Module\b') {
            "# $line"
        }
        else {
            $line
        }
    }

    Set-Content -Path $targetPath -Value $modifiedLines -Encoding UTF8
    return Get-Item -Path $targetPath
}