49 lines
1.5 KiB
PowerShell
49 lines
1.5 KiB
PowerShell
function Out-FileWithRetry {
|
|
<#
|
|
.SYNOPSIS
|
|
Use this instead of Tee-Object because this actually lets you bypass errors to some regard
|
|
|
|
.PARAMETER FilePath
|
|
[string] File path to write to
|
|
|
|
.PARAMETER InputObject
|
|
[PSObject] Pipeline fed object
|
|
|
|
.PARAMETER Append
|
|
[switch] Used to indicate if the file should be overwritten or appended. Force is assumed in either regard.
|
|
|
|
.EXAMPLE
|
|
"My log message" | Tee-OutFile -Append -FilePath $logFilePath | Write-Host
|
|
#>
|
|
[CmdletBinding()]
|
|
[OutputType([PSObject])]
|
|
param(
|
|
[Parameter(Mandatory=$true, Position = 0)]
|
|
[string]$FilePath,
|
|
[Parameter(Mandatory=$true,ValueFromPipeline = $true)]
|
|
[PSObject]$InputObject,
|
|
[switch]$Append
|
|
)
|
|
begin {
|
|
$logLead = (Get-LogLeadName)
|
|
$FilePathValid = Test-Path $FilePath -IsValid
|
|
}
|
|
process {
|
|
if (!$FilePathValid) {
|
|
Write-Warning "$logLead : Can not log to FilePath [$FilePath] as it is invalid. Still passing output on the pipeline."
|
|
}
|
|
|
|
# Only write if the path was valid in the first place, obviously
|
|
if ($FilePathValid) {
|
|
Invoke-CommandWithRetry -Arguments @($FilePath, $InputObject, $Append) -Milliseconds 100 -JitterMin -10 -JitterMax 100 -ScriptBlock {
|
|
param($FilePath, $InputObject, $useAppend)
|
|
$InputObject | Out-File -Append:$useAppend -Force -FilePath $FilePath
|
|
}
|
|
}
|
|
|
|
return $InputObject
|
|
}
|
|
}
|
|
|
|
Set-Alias -Name Tee-OutFile -Value Out-FileWithRetry
|