PowerShell 如何检查文件是否存在

4

我有一个通过SSIS进程任务调用的PowerShell脚本,用于检查文件是否被锁定 - 我该如何修改它以首先检查文件是否存在。

  • 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}
    

1
https://dev59.com/hVwZ5IYBdhLWcg3wFMzD - Vivek Kumar Singh
1
如果另一篇帖子也是有关复制的,那么这怎么算是重复呢——我的帖子是关于检查它是否存在和是否被锁定的。 - Michael
1个回答

5
$file = "\\xxxxxx\xxxx\xxxxx\xxxxxxxxx\task_status.log"
if (Test-Path -path $file)
{ 
    try { [IO.File]::OpenWrite($file).close();return 0 } catch { return 999}
}
else
{
    return 999
}

如果文件存在但未锁定,我不会得到0吗? - Michael
如果文件存在,它将使用您以前的try/catch并以与之前相同的代码退出。 如果文件不存在,它将返回999。 - Oggew
如果文件存在且未被锁定,为什么我没有得到0呢?我已经在PowerShell中尝试过了。 - Michael
实际上,如果我在 MS Word 中打开日志,它不起作用 - 我应该期望看到 999 吗?在 Powershell 中它什么也没有返回。 - Michael
如果文件不存在,我只会得到一个999。 - Michael
1
尝试将 exit 0 和 exit 999 更改为 return 0 和 return 999。 - Oggew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接