4

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

我有一个 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

4

3 回答 3

14

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

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

于 2015-03-31T22:29:26.793 回答
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.
于 2014-06-11T03:38:30.710 回答
1

我也有同样的情况,就我而言,问题是我从 powershell 命令窗口调用脚本。如果我通过右键单击脚本“使用 Powershell 运行”直接执行脚本,驱动器不会在之后消失。

于 2014-12-03T13:54:09.937 回答