小编Fit*_*ery的帖子

PowerShell If 语句:IF 等于多个特定文本

早上好!我正在编写一个脚本,我正在尝试包含一个基于具有多个特定文本选项的文本变量的 IF/Else 语句,并测试以该变量命名的目录路径,如果没有,则创建该目录不存在。所以例子是

$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")

If($text -match "Specific Text1") -and (!(Test-Path $Path\$text))){

new-item -ItemType directory -path $Path\$text

}
ElseIF($text -match "Specific Text2") -and (!(Test-Path $Path\$text))){

new-item -ItemType directory -path $Path\$text

}

ElseIF($text -match "Specific Text3") -and (!(Test-Path $Path\$text))){

new-item -ItemType directory -path $Path\$text

}

ElseIF($text -notmatch "Specific Text1","Specific Text2","Specific Text3"){
write-host "invalid input"
}
Run Code Online (Sandbox Code Playgroud)

我为用户提供了一个有效输入的列表,可以输入到文本框中。当我尝试运行脚本时,我仍然收到错误消息,指出该文件夹已经存在,但它并没有像应有的那样忽略它。

一个附带问题是否有更简洁的方法来写这个?

编辑

以下是对我来说完美的答案。谢谢大家的回复!

$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If ($text -in $AcceptableText)
{
    If (!(Test-Path $Path\$text)) 
    {
        new-item …
Run Code Online (Sandbox Code Playgroud)

powershell if-statement

6
推荐指数
2
解决办法
490
查看次数

标签 统计

if-statement ×1

powershell ×1