PowerShell: What is the best way to check whether the current user has permission to overwrite a file in PowerShell? PowerShell: What is the best way to check whether the current user has permission to overwrite a file in PowerShell? powershell powershell

PowerShell: What is the best way to check whether the current user has permission to overwrite a file in PowerShell?


I've used this:

Try { [io.file]::OpenWrite($outfile).close() } Catch { Write-Warning "Unable to write to output file $outputfile" }

It will attempt to open the file for write access, then immediately close it (without actually writing anything to the file). If it can't open the file for any reason, it will run the Catch block, and you can do your error handling there.


You could attempt a quick write (append) to the file such as

"" | Out-File 'w:\Temp\non-writable-file.txt' -Append

Where no write permissions exist you will receive an error:

Out-File : Access to the path 'w:\Temp\non-writable-file.txt' is denied.
...
+ CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

You could catch and terminate on that error, in the case where write permission exists - you've just appended a new line to the file.