Reputation: 892
I have a batch script with double if statement. I want to convert it to powershell. I tried this code but it still not working.
My batch script
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
MY Powershell Script
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
}
Upvotes: 0
Views: 322
Reputation: 24071
The original Powershell code contains a bug. Chaining conditions with -and
like so,
(![System.IO.Directory]::Exists("$FE_WKFD\AUTO")) -and
(![System.IO.Directory]::Exists("$FE_WKFD\AUTO\POB")) -and
will mean that create all the directories only if all the directories are missing. In the batch, each dir is tested and created separately.
An idiomatic Powershell approach is to store dirs in a collection, iterate it and create what's missing. The edge case of testing for a file instead of a dir is not shoehorned in the same construct but has its own if
statement.
A further readability improvement is to use simple conditions. Instead of if something and something and so and so
, first test if $Log
is set and then start testing for directories. Like 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
}
Upvotes: 2