TL;DR
At the beginning of my script, I would like to check whether a file (given as a parameter) is overwritable, and quit if the current user does not have permission to do that.
(For example, if the user or the group he/she belongs to has been denied access for a file.)
The reason: in the script, I'm processing some data (which takes time), and at the end, I write the results into a file, but it would be a bit frustrating that the whole script ran correctly, but at the end, it turns out that the file is not writable (which I could have checked at the beginning).
What I tried
This is a correct way to test whether a file exists:
$Outfile = "w:\Temp\non-writable-file.txt" # (normally I get this as a parameter)
$OutFileExists = Test-Path -Path $Outfile -PathType Leaf
Of course, $OutfileExists
will be equal to True
if the file exists.
But I would like to check whether this file is writable - now it's not (I changed the security settings myself to be able to test it):
So, if I try this:
(Get-Acl $Outfile).Access
I get this output:
FileSystemRights : Write
AccessControlType : Deny
IdentityReference : Everyone
IsInherited : False
InheritanceFlags : None
PropagationFlags : None
FileSystemRights : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : Everyone
IsInherited : False
InheritanceFlags : None
PropagationFlags : None
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : DOESNTMATTER\Pete
IsInherited : False
InheritanceFlags : None
PropagationFlags : None
(I could also have filtered this result.)
OK, now I know that the Everyone group has no write access.
But I still don't know how to check the overwritability of this file elegantly.