【发布时间】:2021-02-09 18:46:15
【问题描述】:
脚本正确挂载驱动,但重启机器后驱动没有持久化:
function RemapDrive {
param(
$DriveLetter,
$FullPath,
$Credential
)
Write-Host "Trying to remove $DriveLetter in case it already exists ..."
# $DriveLetter must be concatenated with ":" for the command to work
net use "${DriveLetter}:" /del
## $DriveLetter cannot contain ":"
$psDrive = New-PSDrive -Name "$DriveLetter" -PSProvider "FileSystem" -Root "$FullPath" -Credential $Credential -Scope "Global" -Persist
Write-Host "$DriveLetter was successfully added !"
}
function BuildCredential {
param (
$Username,
$Password
)
$pass = ConvertTo-SecureString $Password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($Username, $pass)
return $credential
}
$credential = (BuildCredential -Username "xxxxxx" -Password "yyyyyy")[-1]
RemapDrive -DriveLetter "X" -FullPath "\\my-server\x" -Credential $credential
我发现了什么:
“当您在本地范围内(即没有点源)时,Persist 参数不会将 PSDrive 的创建持续到您运行命令的范围之外。如果您在脚本中运行 New-PSDrive,并且希望新驱动器无限期地持续存在,则必须对脚本进行点源。为获得最佳结果,要强制新驱动器持续存在,除了将 Persist 添加到命令中之外,还要将 Global 指定为 Scope 参数的值。”
我尝试使用“. .\my-script.ps1”执行脚本(对脚本进行点源?),但结果是一样的。
玩弄“网络使用”和注册表以尝试添加网络驱动器也让我陷入了死胡同。
规格:
Windows 10 家庭版
Powershell 版本:
Major Minor Build Revision
----- ----- ----- --------
5 1 18362 1171
【问题讨论】:
-
@TheGameiswar "您需要从以登录 Windows 的同一用户身份运行的 PowerShell 会话映射驱动器" $env:UserName in情况下我遗漏了一些明显的东西)。但是您的链接可能会帮助其他找到我的问题的人。
-
我们在工作中遇到了同样的问题,但我们解决了;我只是不记得如何,但是,我会搜索我们的脚本,让它工作。认为这就像在
-Persist之后提供“是”一样简单。
标签: powershell