0

我有一个将映射的网络共享保存到 txt 文件的注销脚本:

#File path for save
$TxtPath = "C:\temp\" + "$env:UserName" + ".txt"

#Clear existing entries in file
Clear-Content -Path $TxtPath

#Return drive letters
$DriveList = Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-b:d-g:i-z]$'

#Get path for each drive letter and save in specific format (letter;path)
Foreach($Item in $DriveList){
$DrivePath = (Get-PSDrive $Item).DisplayRoot
$Entry = -join($Item, ":", ";", $DrivePath)
Add-Content -Path $TxtPath -Value ($Entry)
}

然后我有一个登录脚本来重置和映射这些驱动器:

#File path for user drive paths
$TxtPath = "C:\temp\" + "$env:UserName" + ".txt"

#Get current drives
$DriveList = Get-PSDrive | Select-Object -ExpandProperty 'Name' | Select-String -Pattern '^[a-b:d-g:i-z]$'

#Remove current drives
ForEach($Item in $DriveList){
    $Drive = -join($Item, ":")
    net use $Drive /delete
}

#Map network drives from file
ForEach($Line in Get-Content $TxtPath) {
    $DriveLetter,$DrivePath = $Line.split(';')
    net use $DriveLetter $DrivePath
}

我的问题是,因为我使用 net use 删除和映射驱动器(在登录脚本中),注销脚本中的 Get-PSDrive 函数不返回驱动器路径。我在 Remove-PSDrive 上使用 net use 的原因是驱动器没有被完全删除(仍然显示在用户设备上)。

当我使用 net use (net use Z:) 查找网络共享时,有人能告诉我如何捕获网络共享的远程名称值吗?如果我可以简单地捕获此路径(并且仅捕获此路径),我将能够将其与驱动器号一起写入文本文件,从而解决我的问题。

我知道我可以通过将数据保存到文件来捕获网络使用的结果:

net use x: > C:\Temp\output.txt

但是我无法将此数据/单行所需信息保存到变量中。任何帮助将非常感激。

4

1 回答 1

1

一种方法是直接查看注册表:

Get-ChildItem "HKCU:Network\" |
    ForEach-Object {
        [PsCustomObject]@{
            DriveLetter = $_.PSChildName
            RemotePath = (Get-ItemProperty $_.PSPath).RemotePath
        }
    }

这将给出如下输出:

DriveLetter RemotePath                
----------- ----------                
M           \\server1\share1 
N           \\server2\share2   
O           \\server3\share3

要保存到文件,我建议在最后一个括号后添加 CSV 格式:

| Export-Csv <path>\MappedDrive.csv

然后,您可以使用 轻松地再次导入数据Import-Csv

于 2018-05-30T10:24:15.180 回答