rit*_*ydh 3 powershell drive-mapping windows-server-2012
我已经尝试过寻找几天没有运气的答案......
我有一个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
Run Code Online (Sandbox Code Playgroud)
显然,这里的问题是在脚本中运行命令但是如何解决这个问题呢?我需要在服务器重启后自动映射驱动器.使用UNC路径不起作用,因为我使用的软件不理解它们.
编辑:忘了说我正在运行的操作系统是Windows Server 2012
脚本在什么用户帐户下运行?该脚本必须以将使用该驱动器的用户身份运行。来自获取帮助:
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8184 次 |
| 最近记录: |