首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何处理使用powershell比较现有文件的if语句?

如何处理使用powershell比较现有文件的if语句?
EN

Stack Overflow用户
提问于 2019-06-18 02:35:49
回答 1查看 521关注 0票数 1

我有一个函数和if语句。我想检查一个文件夹和文件的所有存在性,然后做一些事情。

我尝试了这段代码,我使用了-and,但是它只检查第一个文件夹,如果第一个文件夹不存在,它将执行下一个进程,它不逐个检查文件夹和文件,然后执行下一个进程。

代码语言:javascript
复制
Function Call
{
& .\run.cmd
start-Sleep -s 1 
$Log = Get-Content .\log.txt | Where-Object {$_.Contains("111")}

if(
    ($Log) -and 
    (![System.IO.Directory]::Exists("$FilePath\AGM")) -and 
    (![System.IO.Directory]::Exists("$FilePath\GM\JOB")) -and
    (![System.IO.Directory]::Exists("$FilePath\GM\PO")) -and
    (![System.IO.Directory]::Exists("$FilePath\GM\GM.flg"))
){
        New-Item -ItemType Directory -Force -Path "$FilePath\GM"
        New-Item -ItemType Directory -Force -Path "$FilePath\GM\JOB"
        New-Item -ItemType Directory -Force -Path "$FilePath\GM\PO"
        New-Item -ItemType File -Force -Path "$FilePath\GM\GM.flg"

    CHK_STAGE

} 
else 
{
    END
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-18 03:17:15

这是完全按照设计的操作。只有一个带有几个子句的if语句连接到-and,这意味着所有语句都必须是$true才能满足条件并输入块。

您真正想要的是四个单独的if语句,每个语句计算一个条件,然后根据结果执行操作。

代码语言:javascript
复制
if($Log) {
    if (![System.IO.Directory]::Exists("$FilePath\AGM")) {
        New-Item -ItemType Directory -Force -Path "$FilePath\GM"
    }

    if (![System.IO.Directory]::Exists("$FilePath\GM\JOB")) {
        New-Item -ItemType Directory -Force -Path "$FilePath\GM\JOB"
    }

    if (![System.IO.Directory]::Exists("$FilePath\GM\PO")) {
        New-Item -ItemType Directory -Force -Path "$FilePath\GM\PO"
    }

    if (![System.IO.Directory]::Exists("$FilePath\GM\GM.flg")) {
        New-Item -ItemType File -Force -Path "$FilePath\GM\GM.flg"
    }
}

但我还要指出,在创建目录时,if语句是多余的。

你可以这么做:

代码语言:javascript
复制
New-Item -ItemType Directory -Force -Path "$FilePath\GM"
New-Item -ItemType Directory -Force -Path "$FilePath\GM\JOB"
New-Item -ItemType Directory -Force -Path "$FilePath\GM\PO"

无论目录是否已经存在,调用都将成功。它还将返回每个目录。

对于文件调用,如果文件已经存在,它将将文件清零,因此您可以删除-Force,然后使用-ErrorAction Ignore-ErrorAction SilentlyContinue (后者仍然填充$Error,而前者不填充;两者都在没有消息或中断的情况下成功)。

代码语言:javascript
复制
New-Item -ItemType File -Path "$FilePath\GM\GM.flg" -ErrorAction Ignore
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56641058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档