How to verify whether the share has write access?

倾然丶 夕夏残阳落幕 提交于 2019-12-04 16:59:10

This does the same thing as @Christian's C# just without compiling 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'

I'd like to look into implementing GetEffectiveRightsFromAcl in PowerShell because that will better answer the question....

I use this way to check if current user has write access to a path:

# 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.. }

Code doesn't check ACL but just if is possible to write a file in the path, if it is possible returns string 'allowed' else return the exception's message error.

Here's a pretty simple function I built. It returns "Read", "Write", "ReadWrite", and "" (for no access):

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!