Map drive inside function

Hi

I have the following code:

function Check-PreReq {
    
    Param(
        [string]$Letter,
        [string]$Path
    )
    if (!(Test-Path $($Letter+":") -ErrorAction Ignore)){
        $DriveParams = @{ErrorAction = "Stop"}
        $DriveParams.PSProvider = "FileSystem"
        $DriveParams.Name = $Letter
        $DriveParams.root = $Path
        $DriveParams.Persist = $true

        if (!(Test-Path $Path -ErrorAction Ignore)){
            if (!($creds)){
                $creds = Get-Credential
                $DriveParams.Credential = $creds
            }
        }
        try{
            New-PSDrive @DriveParams
        }catch{
            "Something went wrong: " + $_.Exception.Message
        }
        dir h:
    }
}
Check-PreReq -Letter "h" -Path "\\Server\Shares\conlhm"

It seams to work, but I think the mapped drive only works inside the function.
I then tried this:

function Check-PreReq {
    
    Param(
        [string]$Letter,
        [string]$Path
    )
    if (!(Test-Path $($Letter+":") -ErrorAction Ignore)){
        $DriveParams = @{ErrorAction = "Stop"}
        $DriveParams.PSProvider = "FileSystem"
        $DriveParams.Name = $Letter
        $DriveParams.root = $Path
        $DriveParams.Persist = $true

        if (!(Test-Path $Path -ErrorAction Ignore)){
            if (!($creds)){
                $creds = Get-Credential
                $DriveParams.Credential = $creds
            }
        }
    }
    return $DriveParams
}
$Params = Check-PreReq -Letter "h" -Path "\\server\Shares\conlhm"
New-PSDrive @Params

Which is working, (Just for testing, not finish) but not “The way I want it :)”

So is there a way in the first code, to make the drive usable to the hole script?

Thanks

Functions are a scoped element in PowerShell; variables and such created in one exist only within them. New-PSDrive has a -scope parameter if your goal is to have the function pollute the global scope.

Yeah, so it’s doable, I just don’t know why you’d be doing this. This looks like a pretty thin wrapper over New-PSDrive – why not just use the builtin function?