[英]PowerShell: What is the best way to check whether the current user has permission to overwrite a file in PowerShell?
在腳本的開頭, 我想檢查文件(作為參數)是否可重寫,如果當前用戶沒有權限執行此操作,請退出 。
(例如,如果拒絕了用戶或他/她所屬的組訪問文件。)
原因是:在腳本中,我正在處理一些數據(這需要時間),最后,我將結果寫入文件中,但是整個腳本正確運行會有些令人沮喪,但是最后,結果文件是不可寫的(我本來可以檢查的)。
這是測試文件是否存在的正確方法:
$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組沒有寫訪問權限。
但是我仍然不知道如何優雅地檢查此文件的可重寫性。
我用了這個:
Try { [io.file]::OpenWrite($outfile).close() }
Catch { Write-Warning "Unable to write to output file $outputfile" }
它將嘗試打開文件進行寫訪問,然后立即將其關閉(實際上不向文件寫入任何內容)。 如果由於某種原因無法打開文件,它將運行Catch塊,您可以在此處進行錯誤處理。
您可以嘗試快速寫入(附加)到文件,例如
"" | Out-File 'w:\Temp\non-writable-file.txt' -Append
如果沒有寫權限,您將收到一個錯誤:
文件外:拒絕訪問路徑“ w:\\ Temp \\ non-writable-file.txt”。
...
+ CategoryInfo:OpenError:(:) [Out-File],UnauthorizedAccessException
+ FullyQualifiedErrorId:FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
在存在寫權限的情況下,您可以捕獲並終止該錯誤-您剛剛在文件中添加了新行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.