Match strings stored in variables using PowerShell

家住魔仙堡 提交于 2019-12-12 09:46:46

问题


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

$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:

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

This returns true.


回答1:


I'd say use wilcards and the like operator, it can save you a lot of head aches:

$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:

$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))


来源:https://stackoverflow.com/questions/10400035/match-strings-stored-in-variables-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!