powershell - 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\$_";
}
}
解决方案
- 我缺少一个明确的问题/错误报告。
- 您的模式从输入中获取所有数字
(贪婪) ,\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
}
推荐阅读
- python - 在二维中可视化集群时,轴上的数字是什么意思?
- java - 系统找不到指定的文件 - Netbeans Maven 项目
- amazon-s3 - 使用没有 Route 53 的 AWS S3 + Cloud Front 托管静态网站
- javascript - 在不等待的情况下访问 setTimeout 承诺的值
- python - 如何使用 sys.stdin.readline()?
- ios - Siri 快捷方式 iOS 13 错误 INUIAddVoiceShortcutButton
- python - 如何在 SQLAlchemy 核心中为缺失值插入 NULL?
- amazon-s3 - Redshift 外部表显示 NULL 的实际时间戳值
- selenium - RecaptchaV3 为 Selenium 返回 0.9 分
- visual-studio-code - 为什么我的 VSCode 调试器在 Method.class 文件中停止?