Tag Archives: locked file

Get-FileInfo

Had to retrieve information if a filed was locked and who owned it – so wrote the below Powershell function. Ways to improve would perhaps be to provide parsing of multiple-files.

<?Function Get-FileInfo {
<#
.SYNOPSIS
Retrieves file-information, such as size, name and locks
.DESCRIPTION
Outputs an object with Path, Size, Created on, Last Write Time,
Owner and if the file is locked
.EXAMPLE
Get-FileInfo -File c:\windows\regedit.exe
#>
[CmdletBinding()]
param(
[Parameter(mandatory=$true)]
[string]$File
)
Begin
{
write-verbose "------------------------"
write-verbose "Start of Get-FileInfo"
write-verbose "Computername:  $($env:computername)"
write-verbose "Username: $($env:USERNAME)"
Write-verbose "Validate file $($file)"

if (Test-Path  $($file))
{
Write-Verbose "File exists"
}
else
{
throw-error "File does not exist"
}

}
Process
{

#Retrieve file object
$objfile = Get-ChildItem $file

#check file lock
try { [IO.File]::OpenWrite($objfile).close();$lock = $false }
catch {$lock = $true}

#output object
New-Object PSObject -Property @{
Path = $objFile.fullname
Size = "{0:N2} MB" -f ( $objFile.Length / 1mb )
'Created on' = $objFile.CreationTime
'Last Write Time' = $objFile.LastWriteTime
Owner = (Get-Acl $File).Owner
Lock = $lock

}

}
End
{
write-verbose "End of Get-FileInfo"
write-verbose "------------------------"
}
}