我已经尝试了几天没有运气的寻找答案...
我有一个 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