简体   繁体   English

使用PowerShell匹配存储在变量中的字符串

[英]Match strings stored in variables using PowerShell

I am attempting to create a backup script that will move files that are older that 30 days, but I want to be able to exclude folders from the list 我正在尝试创建一个备份脚本,该脚本将移动30天以前的文件,但我希望能够从列表中排除文件夹

$a = "C:\\Temp\\Exclude\\test"
$b = "C:\\Temp\\Exclude"

if I run the following: 如果我运行以下内容:

$a -match $b

Following PowerShell Basics: Conditional Operators -Match -Like -Contains & -In -NotIn : 遵循PowerShell基础:条件运算符-Match -Like -Contains&-In -NotIn

$Guy ="Guy Thomas 1949"
$Guy -match "Th"

This returns true . 这返回true

I'd say use wilcards and the like operator, it can save you a lot of head aches: 我会说使用wilcards和类似的操作符,它可以为你节省很多头痛:

$a -like "$b*"

The match operator is using regex pattern and the path is having regex special characters in it (the escape characeter). 匹配运算符使用正则表达式模式,路径中包含正则表达式特殊字符(转义符号)。 If you still want to use -match - make sure to escape the string: 如果您仍想使用-match - 请确保转义字符串:

$a -match [regex]::escape($b)

This will work but keep in mind that it can match in the middle of the string, you can add the '^' anchor to tell the regex engine to match from the begining of the string: 这将工作,但请记住,它可以匹配在字符串的中间,你可以添加'^'锚点告诉正则表达式引擎匹配字符串的开头:

$a -match ("^"+[regex]::escape($b))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM