我的-replace运算符出了什么问题?

时间:2016-10-13 09:53:07

标签: powershell powershell-v4.0

我正在尝试更改所有VMS的VM路径,以将它们移动到不同的挂载点:

$oldmount = "C:\RAID-5"
$newmount = "D:"

$drives = Get-VM | Get-VMHardDiskDrive
foreach ($drive in $drives)
{
    $path = $drive.path
    $path -replace $oldmount, $newmount     # just show what the new path will look like
}

如果我运行上面的脚本,我会收到这些错误:

The regular expression pattern C:\RAID-5 is not valid.
At C:\Users\mark\Documents\ChangeAllVMDrives.ps1:8 char:5
+     $path -replace $oldmount, $newmount
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (C:\RAID-5:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

我做错了什么?

1 个答案:

答案 0 :(得分:1)

-replace正在使用正则表达式,因此您必须使用[regex]::Escape() 转义

# ....
 $path -replace [regex]::Escape($oldmount), $newmount     # just show what the new path will look like

或者您可以使用字符串类方法Replace()

$path.Replace($oldmount, $newmount)
相关问题