Map drive inside function

This topic contains 2 replies, has 3 voices, and was last updated by  Joel Sallow 2 weeks, 1 day ago.

  • Author
    Posts
  • #103667

    nOrphf
    Participant

    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

  • #103693

    Don Jones
    Keymaster

    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.

  • #103727

    Joel Sallow
    Participant

    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?

You must be logged in to reply to this topic.