首页 > 解决方案 > Powershell 模式匹配

问题描述

我需要根据来自远程服务器上的订单输入数据库的 9 位数字和前导零主键创建目录。
每天早上应该创建一个新目录。目录名称将是新客户的主键编号。我已经有了使用 BCP 将主键信息提取到文本文件中的 sql 语句,该 BCP 保留了前导零。
该文件从数据库服务器传输到需要创建文件夹的本地目录。使用我认为我发现的一些 PowerShell 代码尝试从我一直在修改的文本文件中创建文件夹。
我需要在文件夹名称中保留前导零,以便稍后在项目中引用回数据库。我的问题是,当我运行 PowerShell 脚本时,没有创建任何文件夹。我认为我的问题与模式定义隔离,但不明白出了什么问题。

输入txt文件示例

001132884
001454596
001454602
001454605
001454606
001454601
001107119
001454600
001454608

PowerShell 脚本

$folder="Customerdocuments";   # Directory to place the new folders in.
$txtFile="E:\dirtext.txt";     # File with list of new folder-names
$pattern="\d+.+";              # Pattern that lines must match      


Get-Content $txtFile | %{

    if($_ -match $pattern)
    {
        mkdir "$folder\$_";
    }
}

标签: powershell

解决方案


  • 我缺少一个明确的问题/错误报告。
  • 您的模式从输入中获取所有数字(贪婪) ,\d+
    并且至少需要一个其他(任何)字符.+,该字符不存在于您的示例文件中。
  • 所以你的问题与前导零无关。
  • 最好准确指定 9 位数字并将其放入 Where 对象中,
  • $folder 的路径将相对于当前文件夹,应该使用Join-Path
  • 由于 mkdir 只是New-Item的包装函数,它支持管道输入,我会直接使用它。
$folder="Customerdocuments";   # Directory to place the new folders in.
$txtFile="E:\dirtext.txt";     # File with list of new folder-names
$pattern="^\d{9}$"             # Pattern that lines must match      

Get-Content $txtFile | Where-Object {$_ -match $pattern}|
    New-Item -Path {Join-Path $folder $_} -ItemType Directory | Out-Null
}

推荐阅读