gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:46:59 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于powershell - 退出 powershell 脚本后,通过 New-PSDrive 映射的网络驱动器消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com