Powershell New-PSDrive一致性

时间:2018-10-21 08:59:37

标签: windows powershell vmware vmware-workstation

我创建了一个从本地PC运行的脚本,并使用invoke-command将文件从主机1复制到主机2。

相关部分:

$session =New-PSSession -Computername $Thost -Credential $mycreds

Invoke-Command -Session $session -ScriptBlock  {
#seting a temp drive on Host for simple approch
Remove-PSDrive -Name w -Force
New-PSDrive -Name w -PSProvider FileSystem -Root $Using:VMPath -Credential $Using:mycreds -ErrorAction Stop
Write-Host "You Chose that $Using:OSVersion will be copyed to $Using:Thost"
Copy-Item -Path "w:\$Using:OSVersion" -Destination $using:VMXPath   -Recurse
Remove-PSDrive -Name w -Force -ErrorAction Stop
 }

我第一次运行脚本时运行得很好! First Run of the Script

第二次说PSdrive不存在。 Second Run Error in PowerShell

10分钟后+-脚本再次正常运行

1 个答案:

答案 0 :(得分:0)

我很惊讶它第一次运行。看来故障是在最初的Remove-PSDrive上。它失败了,因为您已经卸下了w驱动器。

采用这两种模型之一

Remove-PSDrive -Name w -ErrorAction SilentlyContinue
New-PSDrive -Name w -PSProvider FileSystem -Root c:\test
Remove-PSDrive -Name w -Force

OR

if (Test-Path -Path w:\){
   Remove-PSDrive -Name w -Force
 }
 New-PSDrive -Name w -PSProvider FileSystem -Root c:\test
 Remove-PSDrive -Name w -Force

我会选择第二个选项