Powershell:映射的网络驱动器在重启后消失

问题描述 投票:0回答:1

我需要创建某种自动化解决方案,用于使用新凭据重新映射网络驱动器,但执行此操作的人无法知道凭据。为此,我认为

PowerShell
脚本将是最好的解决方案,所以我在下面写了一个。 脚本运行良好,一切正常,但是**映射驱动器在重新启动后消失。**你知道我应该采取什么不同的措施或其他方法来使该映射驱动器持续存在吗?

这是脚本:

Net use * /delete /yes

$username = "domain\username"
$pwdFile = "$env:USERPROFILE\Desktop\xxx_mapping\fs_pwd.txt"
$keyFile = "$env:USERPROFILE\Desktop\xxx_mapping\AES.key"
$key = Get-Content $keyFile
$password = Get-Content $pwdFile | ConvertTo-SecureString -Key $key
$fs_path = "\\pathTo\Share"
$driveLetter = "P"
New-PSDrive -Name $driveLetter -PSProvider "FileSystem" -Root $fs_path -Credential (New-Object System.Management.Automation.PSCredential($username, $password)) -Persist

$filePath = "C:\Windows\someFile"
$fileContent = Get-Content -Path $filePath
foreach ($line in $fileContent) {
    if ($line -match "Path of the Remote Work Directory=(.*)") {
        $remoteWorkDirectory = $matches[1].Trim()
        $computerName = $env:COMPUTERNAME
        $outputString = "$remoteWorkDirectory-$computerName"
        Add-Content -Path "P:\evidenceFile.txt" -Value $outputString
    }
}

Remove-Item -Path "$env:USERPROFILE\Desktop\xxx_mapping" -Recurse

代码解释:

  1. 我想删除以前映射的驱动器,所以有
    net use
    命令
  2. 密码在文件中受到保护,因此您可以在其中看到一堆与密码相关的变量
  3. 完成映射后,配置文件中的证据行将复制到共享驱动器上的另一个文件
  4. 完成后,桌面上的文件夹被删除
powershell persist net-use new-psdrive
1个回答
0
投票

New-PSDrive的文档有这样的说法:

如果您在脚本内运行 New-PSDrive,并且希望驱动器无限期地保留,则必须对脚本进行点源化。为了获得最佳结果,要强制新驱动器无限期地保留,请将 Scope 参数添加到命令中,并将其值设置为 Global。有关点源的更多信息,请参阅about_Scripts

PSDrive 是在运行 New-PSDrive 命令的范围内创建的。当该命令在脚本中运行时,驱动器映射是脚本的本地驱动器映射。当脚本退出时,驱动器不再可用。

为了确保驱动器在脚本之外可用,您必须使用 Scope 参数在全局范围内创建驱动器。

考虑到这一点,将

-scope global
开关添加到您的命令中:

New-PSDrive -Name $driveLetter -PSProvider "FileSystem" -Root $fs_path -Credential (New-Object System.Management.Automation.PSCredential($username, $password)) -Persist -Scope "Global"

尽管如此,老实说我怀疑这是否能解决问题。我发现 Windows 中的网络映射非常不稳定,大多数组织选择在组策略中包含一个登录脚本,该脚本会在用户每次登录时重新映射每个所需的网络驱动器。

您可能已经知道,但我想提一下,您使用另一个帐户的凭据为用户映射网络驱动器的方法是不安全的,虽然密码已加密,但解密密钥也存储在用户可以查看的位置,因此获取密码将是一个简单的过程。 显而易见的解决方案是授予单个用户访问文件共享的权限,但在这种情况下您可能无法执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.