如何验证共享是否具有写访问权限?

时间:2012-03-16 10:19:24

标签: powershell powershell-v2.0

我正在分享写访问权限。我正在编写一个powershell脚本来在该共享中编写日志文件。

我想在写入之前检查我是否具有对此共享的写访问权限的条件。

如何使用PowerShell检查写访问/完全控制?

我尝试过使用Get-ACL cmdlet。

 $Sharing= GEt-ACL "\\Myshare\foldername
    If ($Sharing.IsReadOnly) { "REadonly access" , you can't write" }

它具有Isreadonly属性,但有没有办法确保用户具有Fullcontrol访问权限?

3 个答案:

答案 0 :(得分:7)

这与@ Christian的C#完全相同,只是没有编译C#。

function Test-Write {
    [CmdletBinding()]
    param (
        [parameter()] [ValidateScript({[IO.Directory]::Exists($_.FullName)})]
        [IO.DirectoryInfo] $Path
    )
    try {
        $testPath = Join-Path $Path ([IO.Path]::GetRandomFileName())
        [IO.File]::Create($testPath, 1, 'DeleteOnClose') > $null
        # Or...
        <# New-Item -Path $testPath -ItemType File -ErrorAction Stop > $null #>
        return $true
    } catch {
        return $false
    } finally {
        Remove-Item $testPath -ErrorAction SilentlyContinue
    }
}
Test-Write '\\server\share'

我想在PowerShell中实现GetEffectiveRightsFromAcl,因为这样可以更好地回答这个问题....

答案 1 :(得分:2)

我用这种方式检查当前用户是否具有对路径的写访问权:

# add this type in powershell

add-type @"
using System;
using System.IO;

public class CheckFolderAccess {

 public static string HasAccessToWrite(string path)
        {
            try
            {
                using  (FileStream fs = File.Create(Path.Combine(path, "Testing.txt"), 1, FileOptions.DeleteOnClose))
                { }
                return "Allowed";
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

}
"@

# use it in this way:

if ([checkfolderaccess]::HasAccessToWrite( "\\server\share" ) -eq "Allowed") { ..do this stuff } else { ..do this other stuff.. }

代码不检查ACL,但只是可以在路径中写入文件,如果可能返回字符串'allowed',则返回异常的消息错误。

答案 2 :(得分:1)

这是我构建的一个非常简单的功能。它返回&#34; Read&#34;,&#34; Write&#34;,&#34; ReadWrite&#34;和&#34;&#34; (无法访问):

function Test-Access()
{
    param([String]$Path)
    $guid = [System.Guid]::NewGuid()
    $d = dir $Path -ea SilentlyContinue -ev result
    if ($result.Count -eq 0){
        $access += "Read"
    }   
    Set-Content $Path\$guid -Value $null -ea SilentlyContinue -ev result
    if ($result.Count -eq 0){
        $access += "Write";
        Remove-Item -Force $Path\$guid
    }   
    $access
}