首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在powershell中使用双if语句?

如何在powershell中使用双if语句?
EN

Stack Overflow用户
提问于 2019-06-13 13:57:01
回答 1查看 148关注 0票数 0

我有一个带有双if语句的批处理脚本。我想把它转换成powershell。我试过这段代码,但它仍然不能工作。

我的批处理脚本

代码语言:javascript
复制
IF %ERRORLEVEL% equ 1 (
    IF NOT EXIST %FE_WKFD%\AUTO MKDIR %FE_WKFD%\AUTO
    IF NOT EXIST %FE_WKFD%\AUTO\POB MKDIR %FE_WKFD%\AUTO\POB
    IF NOT EXIST %FE_WKFD%\AUTO\file MKDIR %FE_WKFD%\AUTO\file
    IF NOT EXIST %FE_WKFD%\AUTO\Auto.txt ECHO Auto Text >> %FE_WKFD%\AUTO\Auto.txt
    GOTO B_F
)
GOTO Stop_F

我的Powershell脚本

代码语言:javascript
复制
Function GUI_Choose
{
  & "C:\Users\run.cmd"
  Start-Sleep -s 1 
  $Log = Get-Content "C:\Users\log.txt" |
    Where-Object {$_.Contains("1")}
#####This part convert from batch file#####
  if($Log -and 
    (![System.IO.Directory]::Exists("$FE_WKFD\AUTO")) -and
    (![System.IO.Directory]::Exists("$FE_WKFD\AUTO\POB")) -and
    (![System.IO.Directory]::Exists("$FE_WKFD\AUTO\file")) -and
    (![System.IO.Directory]::Exists("$FE_WKFD\AUTO\Auto.txt"))
    {
     New-Item -ItemType Directory -Force -Path "$WKFD_Path\AUTO"
     New-Item -ItemType Directory -Force -Path "$WKFD_Path\AUTO\POB"
     New-Item -ItemType Directory -Force -Path "$WKFD_Path\AUTO\file"
     New-Item -ItemType Directory -Force -Path "$WKFD_Path\AUTO\Auto.txt"
     }
    B_F #Another Function
}
else
{
    Stop_F #Another Function
}
$FE_WKFD = "C:\Users\"
if(Test-Path -Path "$FE_WKFD\Auto. txt"){
    AUTO #Another FUnction
}
else
{
    GUI_Choose
}
EN

回答 1

Stack Overflow用户

发布于 2019-06-13 15:28:04

原始的Powershell代码包含一个错误。使用-and链接条件,如下所示

代码语言:javascript
复制
(![System.IO.Directory]::Exists("$FE_WKFD\AUTO")) -and
(![System.IO.Directory]::Exists("$FE_WKFD\AUTO\POB")) -and

将意味着只有在所有目录缺失的情况下才创建所有目录。在批处理中,分别测试和创建每个dir。

一种惯用的Powershell方法是将目录存储在集合中,对其进行迭代,然后创建缺少的目录。测试文件而不是目录的边缘用例不是硬塞在相同的构造中,而是有它自己的if语句。

进一步的可读性改进是使用简单的条件。首先测试是否设置了$Log,然后开始测试目录,而不是if something and something and so and so。就像这样,

代码语言:javascript
复制
if($Log) {
    # A list of subdirectories 
    $autoDirs = @("AUTO", "AUTO\POB", "AUTO\file")
    # Iterate subdir list using foreach % operator
    $autoDirs | % {
        # See if subdir exists. $_ is picked from $autoDirs
        if(-not test-path $_) {
            # ... and create if doesn't
            new-item -itemtype directory -path $(join-path $WKFD_Path $_)
        }
    }
    # Create file if it doesn't exist
    if(-not test-path "$WKFD_Path\AUTO\Auto.txt") {
        new-item -itemtype file -path "$WKFD_Path\AUTO\Auto.txt" -value "Auto text"
    }
    B_F

} else {
    Stop_F
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56574165

复制
相关文章

相似问题

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