13

TL;博士

在我的脚本开始时,我想检查一个文件(作为参数给出)是否可覆盖,如果当前用户没有权限则退出
(例如,如果用户或他/她所属的组已被拒绝访问文件。)

原因:在脚本中,我正在处理一些数据(这需要时间),最后,我将结果写入文件,但是整个脚本运行正确会有点令人沮丧,但最后,事实证明该文件不可写(我可以在开始时检查)。


我试过的

这是测试文件是否存在的正确方法:

$Outfile = "w:\Temp\non-writable-file.txt"                # (normally I get this as a parameter)
$OutFileExists = Test-Path -Path $Outfile -PathType Leaf

当然,$OutfileExists将等于True如果文件存在。

但我想检查这个文件是否可写 - 现在不是(我自己更改了安全设置以便能够测试它):

每个人 - 拒绝写作

所以,如果我试试这个:

(Get-Acl $Outfile).Access

我得到这个输出:

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

(我也可以过滤这个结果。)
好的,现在我知道Everyone 组没有写权限。
但是我仍然不知道如何优雅地检查这个文件的可覆盖性。

4

2 回答 2

23

我用过这个:

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

它将尝试打开文件进行写访问,然后立即关闭它(实际上不向文件写入任何内容)。如果由于任何原因无法打开文件,它将运行 Catch 块,您可以在那里进行错误处理。

于 2014-04-08T17:03:18.357 回答
1

您可以尝试快速写入(附加)到文件,例如

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

如果不存在写入权限,您将收到错误消息:

Out-File :拒绝访问路径“w:\Temp\non-writable-file.txt”。
...
+ CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

在存在写权限的情况下,您可以捕获并终止该错误 - 您刚刚在文件中添加了一个新行。

于 2014-04-08T17:47:42.273 回答