Search code examples
filepowershellcmdexistssql-job

CMDExec if exists then stop


I need to have step in SQL Job to check is there file on some path, so if there is file then stop with further execution. Something like:

$file = "\\networklocation\file.bak"
if (-exists (Test-Path $file)) 
{
    throw "$file not found."
}

Solution

  • Just omit the -exists switch and ensure the $ErrorActionPreference is set to stop:

    $ErrorActionPreference = 'stop'
    $file = "\\networklocation\file.bak"
    if (Test-Path $file) 
    {
        throw "$file found."
    }