PoshCode Archive  Artifact Content

Artifact 1af253d69e5a6b041d33448b7e64cbb83df6a4ce320e5ad6a9f41b54ea5256af:

  • File Test-if-file-is-writable.ps1 — part of check-in [c460768058] at 2018-06-10 13:07:40 on branch trunk — Function to test if a file is writable. Uses the .openwrite() method to test and returns a boolean. (user: JimbobNet size: 2119)

# encoding: ascii
# api: powershell
# title: Test if file is writable
# description: Function to test if a file is writable. Uses the .openwrite() method to test and returns a boolean.
# version: 0.1
# type: function
# author: JimbobNet
# license: CC0
# function: Test-IsWritable
# x-poshcode-id: 2236
# x-archived: 2015-08-22T00:53:48
# x-published: 2011-09-16T07:01:00
# Supports -verbose parameter and inline help.
# Path can be provided as a string or as an object to the file.
# Pipeline input is supported. e.g. $bar | get-IsWriteable
# Just updated this to give it the name it should have had to start with…
function Test-IsWritable(){
        Command tests if a file is present and writable.
        Command to test if a file is writeable. Returns true if file can be opened for write access.
        Test-IsWritable -path $foo
		Test if file $foo is accesible for write access.
        $bar | Test-IsWriteable
		Test if each file object in $bar is accesible for write access.
	.Parameter Path
        Psobject containing the path or object of the file to test for write access.
		Write-Verbose "Test if file $path is writeable"
		if (Test-Path -Path $path -PathType Leaf){
			Write-Verbose "File is present"
			$target = Get-Item $path -Force
			Write-Verbose "File is readable"
				Write-Verbose "Trying to openwrite"	
				$writestream = $target.Openwrite()
				Write-Verbose "Openwrite succeded"	
				$writestream.Close() | Out-Null
				Write-Verbose "Closing file"				
				Remove-Variable -Name writestream
				Write-Verbose "File is writable"
				Write-Output $true
				Write-Verbose "Openwrite failed"
				Write-Verbose "File is not writable"
				Write-Output $false
			Write-Verbose "Tidying up"
			Remove-Variable -Name target
			Write-Verbose "File $path does not exist or is a directory"
			Write-Output $false