我的 -replace 运算符有什么问题?
What's wrong with my -replace operator?
我正在尝试更改我所有 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
我做错了什么?
-replace
使用 正则表达式 因此你必须 转义 使用 [regex]::Escape()
:
# ....
$path -replace [regex]::Escape($oldmount), $newmount # just show what the new path will look like
或者您可以使用 .net 字符串 class 方法 Replace()
:
$path.Replace($oldmount, $newmount)
我正在尝试更改我所有 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
我做错了什么?
-replace
使用 正则表达式 因此你必须 转义 使用 [regex]::Escape()
:
# ....
$path -replace [regex]::Escape($oldmount), $newmount # just show what the new path will look like
或者您可以使用 .net 字符串 class 方法 Replace()
:
$path.Replace($oldmount, $newmount)