Answered by:
Powershell check if file exists and is locked

Question
-
I have the below PowerShell script called via a SSIS Process Task to check if a file is locked - how do I modify so it checks if the file exists first.
-
If it does not exist, then exit with 999
-
If it does exist but is locked, then exit with 999
-
If it does exist and is not locked, then exit with 0
$file = "\\xxxxxx\xxxx\xxxxx\xxxxxxxxx\task_status.log" try { [IO.File]::OpenWrite($file).close();exit 0 } catch { exit 999}
Thursday, November 29, 2018 2:33 PM -
Answers
-
I think this may work for you
https://stackoverflow.com/questions/24992681/powershell-check-if-a-file-is-locked
function Test-FileLock { param ( [parameter(Mandatory=$true)][string]$Path ) $oFile = New-Object System.IO.FileInfo $Path if ((Test-Path -Path $Path) -eq $false) { return $false } try { $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($oStream) { $oStream.Close() } $false } catch { # file is locked by a process. return $true } }
- Proposed as answer by ComputerScott Thursday, November 29, 2018 3:18 PM
- Marked as answer by ChairmanMichael Thursday, November 29, 2018 3:26 PM
Thursday, November 29, 2018 3:17 PM
All replies
-
Powershell has a cmdlet for that: Test-Path. Read the complete help including the examples:
Get-Help Test-Path -Full
Live long and prosper!
(79,108,97,102|%{[char]$_})-join''
Thursday, November 29, 2018 2:37 PM -
I have - but I cannot get it to work. If the file exists and\or is not locked, I do not receive a 0
$file = "\\xxxxx\xxxxxx\xxxx\test.log"if (Test-Path -path $file){ try { [IO.File]::OpenWrite($file).close();exit 0 } catch { exit 999}}else{ return 999}
Thursday, November 29, 2018 2:54 PM -
I think this may work for you
https://stackoverflow.com/questions/24992681/powershell-check-if-a-file-is-locked
function Test-FileLock { param ( [parameter(Mandatory=$true)][string]$Path ) $oFile = New-Object System.IO.FileInfo $Path if ((Test-Path -Path $Path) -eq $false) { return $false } try { $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($oStream) { $oStream.Close() } $false } catch { # file is locked by a process. return $true } }
- Proposed as answer by ComputerScott Thursday, November 29, 2018 3:18 PM
- Marked as answer by ChairmanMichael Thursday, November 29, 2018 3:26 PM
Thursday, November 29, 2018 3:17 PM -
Big help thanks - your website is useful.Thursday, November 29, 2018 3:26 PM
-
Wow. Nice little function, and well written. Works like a champ.
-Thanks
Friday, March 27, 2020 7:18 PM