首页 > 解决方案 > 将 test-Path -Path 与正则表达式相结合

问题描述

在 Jenkins 中,我正在创建一个 PowerShell 脚本。这是有效的:

if (Test-Path -Path "$baseDirectory\s*") {...}

但这是“危险的”,不够“安全”。

目录名称将是:sdd 或 sddd (d=digits)。所以名称以字符“s”开头,长度为 2 位和后面的三位数字。

我尝试了以下方法:

if (Test-Path -Path "$baseDirectory\ -match 's(\d{2,3})'") {...}

if (Test-Path -Path "-match '$baseDirectory\s(\d{2,3})'") {...}

和所有的小差异。

如果我使用 s* 执行此操作,则脚本将返回目录名称 s54、s55 等。

如果可能的话,我希望使用正则表达式而不是“找不到目录”得到相同的结果。

标签: regexpowershell

解决方案


您可以使用它来查看是否可以找到具有该名称的一个或多个文件夹。

if ([bool](Get-ChildItem "$baseDirectory\s*" -Directory | Where-Object { $_.Name -match 's\d{2,3}$' })) {
    # your code goes here
}

希望有帮助


推荐阅读