在PowerShell中过滤以(一或两个)斜杠开头的字符串

mah*_*esh 0 regex powershell filter powershell-2.0

我试图找出以一个斜杠(/)和两个斜杠(//)开头的字符串。例如,以下是具有几个字符串的数组:以下是我正在尝试的代码:

$array = @("/website","//windows_service","/console_app","//windows","///IIS","test")
$arraysplit = $array.split(',');
Foreach ($string in $arraysplit)
{
    if ($string.StartsWith("/"))
    {
        Write-Host "$string has one slash."
    }
    elseif($string.StartsWith("//"))
    {
        Write-Host "$string has two slashes."
    }
    else
    {
        #I want to exit only when below conditions meet
        #1. if string doesnot have any slash or
        #2. if string has more than two slashes
        Write-Host "$string has more number of slashes or it doesnot have any slash. Exiting"
        Exit -1
    }
}
Run Code Online (Sandbox Code Playgroud)

我不想写更多的if条件来过滤这些东西,但这不能按预期工作。我认为我应该更改逻辑以达到要求。有人可以建议我吗(我正在寻找动态方法)

Fro*_* F. 5

我会编写一个if-test,使用regex匹配不以一两个斜杠开头的任何行。尝试:

$array = @("/website","//windows_service","/console_app","//windows","///IIS","test")
Foreach ($string in $array)
{
    if ($string -notmatch '^\/{1,2}[^\/]')
    {
        Write-Host "$string has more number of slashes or it doesnot have any slash. Exiting"
        Exit -1
    }
}
Run Code Online (Sandbox Code Playgroud)