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

如何处理使用powershell比较现有文件的if语句?,powershell,Powershell,我有一个带if语句的函数。我想检查文件夹和文件的所有存在性,然后做一些事情 我尝试了这个代码,我使用了-和,但它只检查第一个文件夹,如果第一个文件夹不存在,它将执行下一个过程,它不会逐个检查文件夹和文件,然后执行下一个过程 Function Call { & .\run.cmd start-Sleep -s 1 $Log = Get-Content .\log.txt | Where-Object {$_.Contains("111")} if( ($Log) -and

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

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

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

这是完全按照设计运行的。您有一个带有多个子句的
if
语句,与
-和
连接,这意味着所有这些语句都必须是
$true
,才能满足条件并进入块

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

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
语句是多余的

您可以这样做:

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
,而前者没有;两者都没有消息或中断)


你能告诉我们你到底想做什么吗?
New-Item -ItemType File -Path "$FilePath\GM\GM.flg" -ErrorAction Ignore