退出PowerShell脚本后,通过New-PSDrive映射的网络驱动器消失

时间:2014-06-10 08:14:53

标签: powershell windows-server-2012 drive-mapping

我已经尝试了几天没有运气的答案......

我有一个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路径不会起作用,因为我使用的软件并不理解它们。

编辑:忘了说我正在运行的操作系统是Windows Server 2012

3 个答案:

答案 0 :(得分:11)

我发现即使使用-Persist参数,从登录脚本运行时,驱动器映射也会消失。

通过添加-Scope "Global"参数也解决了问题。

答案 1 :(得分:1)

在哪个用户帐户下运行脚本?该脚本必须以将使用该驱动器的用户身份运行。来自Get-Help:

get-help new-psdrive -parameter Persist
<snipped>
NOTE: Mapped network drives are specific to a user account. Mapped network drives that you create in sessions that 
are started with the "Run as administrator" option or with the credential of another user are not visible in session 
that started without explicit credentials or with the credentials of the current user.

答案 2 :(得分:0)

我有同样的问题,在我的情况下问题是我从powershell命令窗口调用脚本。如果我直接执行脚本并右键单击脚本“Run with Powershell”,则驱动器不会消失。