setting $cred in console from script

This topic contains 2 replies, has 2 voices, and was last updated by  Justin Hull 3 years, 10 months ago.

  • Author
    Posts
  • #11267

    Justin Hull
    Participant

    Heyas all, I have been playing with setting variables and ran into what I think is a scope issue. I was hoping that yall could point me in the right direction

    I like to do a check in my scripts to see if I am logged into the correct account:

    ###############
    ##check account
    $userName = $cred.username
    if($userName -eq $null){
    $cred = Get-Credential
    $userName = $cred.username
    Write-Host "Setting account as: $userName "
    }
    else{
    Write-Host "Running as: $userName "
    }

    When I run ( open powershell.exe > .\test_cred.ps1) this it sees that the $cred is not set and prompts for credentials. If I run the script a second time in the same powershell console it prompts for the credentials again. If I enter $cred = Get-Credential then run the script it sees that $cred is set and does not prompt. This appears to be a scope issue, where I cannot set a console level variable from a script.

    Is there a trick around this? I do not want to use a passwords file or the like.

    Any help would be appreciated

  • #11269

    Dave Wyatt
    Moderator

    If you want a script to set variables in the session that ran it, typically you'd add an extra period and space before the script path. This is called "dot sourcing", and is described in the about_Scripts help file.

    . .\test_cred.ps1
  • #11272

    Justin Hull
    Participant

    sure enough that did it, thank you for the reply

You must be logged in to reply to this topic.