PoshCode Archive  Artifact [5b7d87d9cd]

Artifact 5b7d87d9cdcca5f55714dc13eed87d82c0257c118dc022af24e46c3b01b229ca:

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

# 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: get-IsWritable
# x-poshcode-id: 2235
# x-archived: 2015-08-23T05:35:49
# x-published: 2011-09-16T06:54: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
function get-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.
        get-IsWritable -path $foo
		Test if file $foo is accesible for write access.
        $bar | get-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