我有一个函数和if语句。我想检查一个文件夹和文件的所有存在性,然后做一些事情。
我尝试了这段代码,我使用了-and,但是它只检查第一个文件夹,如果第一个文件夹不存在,它将执行下一个进程,它不逐个检查文件夹和文件,然后执行下一个进程。
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
}
}发布于 2019-06-18 03:17:15
这是完全按照设计的操作。只有一个带有几个子句的if语句连接到-and,这意味着所有语句都必须是$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 Ignorehttps://stackoverflow.com/questions/56641058
复制相似问题