简体   繁体   English

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

[英]Powershell Function Not Mapping Drive When Called

I'm creating a New-PSDrive and mapping over a shared drive. 我正在创建一个New-PSDrive并通过共享驱动器进行映射。 The code runs fine outside of the function as is, but whenever its wrapped within a function I see it try to map the drive. 代码在函数之外运行正常,但是当它包含在函数中时,我看到它尝试映射驱动器。 When I run Get-PSDrive , the specified shared drive is not listed. 当我运行Get-PSDrive ,未列出指定的共享驱动器。

This is the total opposite when running the script outside of the function, I can definitely see the drive mapping over to shared folder after running Get-PSDrive and it's also listed/showing under Computer within Folder Explorer. 这是在函数外部运行脚本时完全相反的情况,我可以在运行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

Using the answer from Getting a free drive letter : 使用获得免费驱动器号的答案:

$letter = Get-ChildItem function:[f-z]: -n | Where { !(Test-Path $_) } | select -First 1

New-PSDrive -Name ($letter)[0] -Root "\\my_server_ip\shared_folder" -Persist -PSProvider Filesystem -Credential (Get-Credential)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM