我有一个带有双if语句的批处理脚本。我想把它转换成powershell。我试过这段代码,但它仍然不能工作。
我的批处理脚本
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脚本
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
}发布于 2019-06-13 15:28:04
原始的Powershell代码包含一个错误。使用-and链接条件,如下所示
(![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。就像这样,
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
}https://stackoverflow.com/questions/56574165
复制相似问题