我试着找了几个,没有运气天的答复后消失......映射网络驱动器退出PowerShell脚本
我有一个PowerShell(V3.0)脚本检查一个网络驱动器并映射它,如果它尚未映射。脚本本身工作得很好,在脚本执行过程中映射和访问驱动器,但脚本结束时,映射的驱动器将断开连接。我正在使用应该保留驱动器映射的-Persist选项。
如果我从PowerShell提示符运行相同的命令,即使在退出PowerShell提示符时,驱动器也会映射并保持映射状态。下面
# Drive letter to map to
$destinationDriveLetter = "G"
# Username to map the network drive
$userName = "username"
# Password to use when mapping
$userPass = ConvertTo-SecureString "password" -AsPlainText -Force
#check if Drive is already mapped
if (Test-Path -LiteralPath $destinationDriveLetter":" -ErrorVariable errVar) {
Write-Host "Drive already mapped.`r`n"
Write-Host "Exiting script`r`n"
exit
}
Write-Host "Destination Driveletter $destinationDriveLetter not mapped. Doing it...`r`n"
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $userPass
Write-Debug "Command: New-PSDrive -Persist -Name $destinationDriveLetter -PSProvider FileSystem -Root '\\server\share' -Credential $Credential -ErrorVariable errVar"
New-PSDrive -Persist -Name $destinationDriveLetter -PSProvider FileSystem -Root '\\server\share' -Credential $Credential -ErrorVariable errVar
if ($errVar) {
Write-Error "`r`nError mapping destination drive $destinationDriveLetter. Check!`r`n"
}
else {
Write-Host "Destination drive mapped successfully.`r`n"
# test if drive truly mapped and destination folder exist
Test-Path -LiteralPath $destinationDriveLetter":" -ErrorVariable errVar
# debugging, roar!
Write-Host "Drives during script:`r`n"
Get-PSDrive
}
# dirty fix to actually confirm that the drive is mapped during script execution
pause
示例代码显然,这里的问题是在脚本中使用命令,但如何解决这一问题?我需要在服务器重启后自动映射驱动器。使用UNC路径将不起作用,因为我使用的软件不理解它们。
编辑:忘了说,OS我正在为Windows Server 2012
在这里回答:http://stackoverflow.com/a/16665256/266876(使用-Scope Global) –