如何从路径中获取特定字符串?

时间:2015-08-12 11:08:33

标签: windows powershell

我想制作一个自动备份脚本,我将在30台不同的计算机上运行。 例如,如果路径是C:\ Users \ PC1,那么我想将所有文件从PC1(C:\ Users \ PC1)复制到C:\ Backup \ PC1,从PC2复制到C:\ Backup \ PC2等等上。因此,我必须询问计算机的路径,获取它的名称并将该名称放在我要保存副本的路径中。我知道我必须使用robocopy进行备份,但我不知道如何从路径中获取pc的名称

1 个答案:

答案 0 :(得分:1)

您可以使用env变量检索Computername:$env:Computername

如果需要解析路径,则应使用Split-Path cmdlet和/或regex。这里使用正则表达式解决您的问题(评论):

 $path = 'C:\myexamplefiles\myfile\bl12\backup'

 # Pick one of these regex:
 $regex = '.*\\bl(..)' # this regex catches any two characters after bl
 $regex = '.*\\bl([^\\]*)' # this regex catches anything after bl until the next slash
 $regex = '.*\\bl(\d\d)' # this regex catches two digits after bl

 [regex]::Match($path, $regex).Groups[1].Value
 #OUTPUT:  12
相关问题