2016-10-13 89 views
1

我想改變我的所有虛擬機的虛擬路徑將其移動到一個不同的安裝點:我的替換操作符有什麼問題?

$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

-replace使用正則表達式因此你必須逃生它使用[regex]::Escape()

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

或者你可以使用串類方法Replace()

$path.Replace($oldmount, $newmount)