Skip to content

Instantly share code, notes, and snippets.

@bender-the-greatest
Last active October 8, 2020 04:05
Show Gist options
  • Save bender-the-greatest/ee78b6c0489924e865d1a45e7adf71a0 to your computer and use it in GitHub Desktop.
Save bender-the-greatest/ee78b6c0489924e865d1a45e7adf71a0 to your computer and use it in GitHub Desktop.
Function to check whether the current user has write permissions to a directory or not
#Requires -Version 6.2
function Get-CanWriteDirectory {
[CmdletBinding()]
Param(
[Parameter(Mandatory, Position=0)]
[ValidateScript(
{ Test-Path -PathType Container $_ },
# Remove this property to make compatible with 5.1, 6.0, and 6.1
ErrorMessage = "Could not find the path or it is not a directory: {0}"
)]
[string]$Path
)
# Make sure temp file doesn't already exist (we clean it up)
$index = 0
$tempFilePath = Join-Path $Path "$($MyInvocation.MyCommand -replace '-')Check$(( $index )).txt"
while( Test-Path -PathType Leaf $tempFilePath ) {
Write-Verbose "${tempFilePath} already exists. Incrementing index..."
$tempFilePath = Join-Path $Path "$($MyInvocation.MyCommand -replace '-')Check$(( ++$index )).txt"
}
# Write temp file to see if we can
$checkPermArgs = @{
Path = $tempFilePath
ErrorAction = 'Stop'
}
Write-Verbose "Writing file ${tempFilePath}"
try {
"$($MyInvocation.MyCommand) check $([DateTime]::Now)" | Out-File @checkPermArgs
} catch {
Write-Verbose "Error writing ""${tempFilePath}"": $($_.Exception.Message)"
return $false
}
# Clean up our messy handiwork
$removeItemArgs = @{
Path = $tempFilePath
ErrorAction = 'Stop'
Force = $true
}
Write-Verbose "Removing file ${tempFilePath}"
try {
Remove-Item @removeItemArgs
} catch {
Write-Warning "Error removing temp file ""${tempFilePath}"": $($_.Exception.Message)"
}
$true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment