调用Powershell函数时不映射驱动器

时间:2017-06-21 14:08:01

标签: powershell

我正在创建一个New-PSDrive并通过共享驱动器进行映射。代码在函数之外运行正常,但是当它包含在函数中时,我看到它尝试映射驱动器。当我运行Get-PSDrive时,未列出指定的共享驱动器。

这是在函数外部运行脚本时的完全相反,我可以在运行Get-PSDrive之后看到驱动器映射到共享文件夹,并且它还列在/显示在“文件夹浏览器中的计算机”下

function MapDrive {

# creates an array of available Drive Letters 
$driveArray = @("A","B","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z")

# check every letter in the array if its available then create a New-PSDrive
foreach ($letter in $driveArray) {
    If (!(Test-Path "$letter`:")) {
        New-PSDrive -Name $letter -Root "\\my_server_ip\shared_folder" -Persist -PSProvider Filesystem -Credential (Get-Credential)
        break
    }
    Else {
        Write-Host "No available Drives."
        break
    }
}

}

MapDrive

Get-PSDrive

1 个答案:

答案 0 :(得分:0)

使用获得免费驱动器号的答案: $ letter = Get-ChildItem函数:[f-z]: - n |其中{!(Test-Path $ _)} |选择 - 第一步 New-PSDrive -Name($ letter)[0] -Root“\\ my_server_ip \ shared_folder”-Persist -PSProvider Filesystem -Credential(Get-Credential)