2014-06-10 74 views
2

我试着找了几个,没有运气天的答复后消失......映射网络驱动器退出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

+0

在这里回答:http://stackoverflow.com/a/16665256/266876(使用-Scope Global) –

回答

1

下运行的是何种用户帐户的脚本?脚本必须以使用该驱动器的用户身份运行。从获取帮助:

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. 
+1

脚本在需要使用驱动器的同一用户下运行。我注意到另一个异常以及...如果我把驱动器映射到一个单独的函数,驱动器映射消失,只要函数结束并且脚本返回到“main”。如果使用if-else比较(如果映射不做任何操作,否则映射它),那么当脚本退出条件时,驱动器映射将丢失。 W00t? :) – ritzydh

+0

如果此脚本正在用户的上下文中运行,则应删除$凭证。这在3台不同账户下的3台电脑上运行,驱动器按预期持续运行。 – StephenP

0

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

9

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

该问题已通过添加-Scope "Global"参数解决。

+1

谢谢soo。这真的有帮助。在我发表评论之前,我正在为此工作几个小时。 – Spencer

相关问题