EvotecIT/PSWriteHTML

Set-Content : Access to the path 'C:\Test.html' is denied.

PrzemyslawKlys opened this issue · 3 comments

Set-Content : Access to the path 'C:\Test.html' is denied.
At C:\Users\przemyslaw.klys\Documents\WindowsPowerShell\Modules\PSWriteHTML\PSWriteHTML.psm1:12230 char:17      
+ ...     $HTML | Set-Content -LiteralPath $FilePath -Force -Encoding $Enco ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Test.html:String) [Set-Content], UnauthorizedAccessException
    + FullyQualifiedErrorId : GetContentWriterUnauthorizedAccessError,Microsoft.PowerShell.Commands.SetContentCommand

Provide workaround in case access to path is denied when saving for EMail/Save-HTML

xlrod commented

Would the desktop of the current user be a good place to save it to?

# Access Denied
if((Test-Path -LiteralPath $FilePath) -eq $true){
    Write-Verbose "Save-HTML - Saved HTML to file $FilePath"
}
else{
    $NewFilePath = Split-Path -Path "$FilePath" -Leaf
    $ErrorMessage = $_.Exception.Message -replace "`n", " " -replace "`r", " " # Not working for me
    Write-Warning "Save-HTML - Failed with error: $ErrorMessage" # Not working for me
    Write-Verbose "Save-HTML - Saving HTML to file $env:USERPROFILE\Desktop\$NewFilePath"    
    $HTML | Set-Content -LiteralPath "$env:USERPROFILE\Desktop\$NewFilePath" -Force -Encoding $Encoding
    if((Test-Path -LiteralPath $NewFilePath) -eq $true){
        Write-Verbose "Save-HTML - Saved HTML to file $env:USERPROFILE\Desktop\$NewFilePath"
    }
    else{
        Write-Verbose "Save-HTML - Failed"
    }
}

You may overwrite someone's file. I guess Temp Directory is better place with random file name but with information to screen where it was saved. You also need try/catch. Would you submit this and other stuff as PR's? :-)

Thank you @xlrod