none
PowerShell script to map network drive using encrypted credentials RRS feed

  • Question

  • Hello

    I would like to make a script that would prompt for credentials and store them as encrypted text.

    Second script would map network drive (net use so it is visible in File Explorer) using encrypted credentials.

    Point of this is so user can enter username and password once and on reboot computer will log into mapped drive automatically. It is important that user credentials are encrypted.

    That's what I have so far.

    Script 1 to get credentials

    $credential = Get-Credential
    $credential.Password | ConvertFrom-SecureString | Set-Content "D:\User_Folders\Desktop\encrypted_password.txt"

    #Do I need one more line to store username?

    Script 2 to use credentials to map drive

    $encrypted = Get-Content "D:\User_Folders\Desktop\encrypted_password.txt" | ConvertTo-SecureString
    Net use W: \\SITSERVER\SITDATA /user:$encrypted /persistent:yes

    It does not work. Also, I am not sure if it saves only password or both username and password.

    Any help is appreciated.

    Thank you very much

    Monday, July 6, 2020 7:41 PM

Answers

  • Try using Export-CliXML to keep user/password together -- securely (at least on Windows machines).

    See here: https://stackoverflow.com/questions/40029235/save-pscredential-in-the-file

    Pay attention to the caveats!


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    • Marked as answer by Invictus91 Monday, July 13, 2020 5:49 PM
    Monday, July 6, 2020 8:12 PM
  • You can use the Persist parameter of New-PSDrive to create Windows mapped network drives.Unlike temporary PowerShell drives, Windows mapped network drives aren't session-specific. They're saved in Windows and they can be managed by using standard Windows tools, such as File Explorer.

    Thank you

    • Marked as answer by Invictus91 Monday, July 13, 2020 5:49 PM
    Tuesday, July 7, 2020 6:46 PM

All replies

  • Try using Export-CliXML to keep user/password together -- securely (at least on Windows machines).

    See here: https://stackoverflow.com/questions/40029235/save-pscredential-in-the-file

    Pay attention to the caveats!


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    • Marked as answer by Invictus91 Monday, July 13, 2020 5:49 PM
    Monday, July 6, 2020 8:12 PM
  • net use expected to get plaintext password, not secure string

    normally old sty command tools have no mechanizms for working with secure string as an input parameters

    you may try to find alternatives in powershell cmdlets instead


    The opinion expressed by me is not an official position of Microsoft

    Monday, July 6, 2020 10:22 PM
  • net use expected to get plaintext password, not secure string

    normally old sty command tools have no mechanizms for working with secure string as an input parameters

    you may try to find alternatives in powershell cmdlets instead


    The opinion expressed by me is not an official position of Microsoft

    Of course!

    Net use W: \\SITSERVER\SITDATA /user:$encrypted /persistent:yes

    becomes

    New-PsDrive W -Root  \\SITSERVER\SITDATA-Persist -Credential $creds


    \_(ツ)_/

    Monday, July 6, 2020 10:34 PM
    Moderator
  • I tried New-PsDrive but it maps drive in "Admin realm". I cannot see it in File Explorer.

    I guess I can make it work but I would much prefer to have drive mapped in "This PC".

    Thank you for your suggestion, though.

    Tuesday, July 7, 2020 6:10 PM
  • Thank you for a great way to store credential together.

    Script 1

    $credential = Get-Credential
    $credential | Export-CliXml -Path 'C:\Users\User\Desktop\credentials.xml'

    Script 2

    $credential = Import-CliXml -Path 'C:\Users\User\Desktop\credentials.xml'

    How do I use $credential variable to map network drive such a way that it appears in File Explorer under "This PC" If I use New-PsDrive the mapping happens in "Admin realm" and user cannot see it in File Explorer.

    Please, is there a way to map it so network drive is visible to users?

    Thank you

    • Proposed as answer by Rav- Tuesday, July 7, 2020 6:42 PM
    • Unproposed as answer by Rav- Tuesday, July 7, 2020 6:42 PM
    Tuesday, July 7, 2020 6:19 PM
  • You can use the Persist parameter of New-PSDrive to create Windows mapped network drives.Unlike temporary PowerShell drives, Windows mapped network drives aren't session-specific. They're saved in Windows and they can be managed by using standard Windows tools, such as File Explorer.

    Thank you

    • Marked as answer by Invictus91 Monday, July 13, 2020 5:49 PM
    Tuesday, July 7, 2020 6:46 PM
  • You're creating the PSDrive in a script? If so, dot-source the script when you run it.

    Also, use both "-Persist" and "-Scope Global" parameters on the New-PSDrive cmdlet.

    Also, have a look at the "Notes" section of the help for the New-PSDrive cmdlet:

    "Mapped network drives are specific to a user account. Mapped drives created in elevated sessions or sessions using the credential of another user aren't visible in sessions started using different credentials."


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Tuesday, July 7, 2020 7:26 PM
  • You're creating the PSDrive in a script? If so, dot-source the script when you run it.

    Also, use both "-Persist" and "-Scope Global" parameters on the New-PSDrive cmdlet.

    Also, have a look at the "Notes" section of the help for the New-PSDrive cmdlet:

    "Mapped network drives are specific to a user account. Mapped drives created in elevated sessions or sessions using the credential of another user aren't visible in sessions started using different credentials."


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    This would only be true (dot sourcing) if the command ere in a function.   The command will work without dot sourcing.

    "Global" should make the drive visible in both an elevated prompt and a non-elevated prompt/session.

    The credentials for mapping apply to the account required to access the share and not to the account the mapping is for.  The commend always maps to the local session.  If that session is elevated then, given GPO settings, it may be only visible in an elevated session.

    The better terminology is to not use "Admin Session" but to state "elevated session".  This correctly describes what is happening.  When logged in with "admin" credentials it is always and "admin session"  What is different is when you "elevate" an admin session.  Elevation just enables the extended security tokens.  These are normally disabled even for admins.  When I say "disabled" I am indicating that the tokens are available but have not been included in the current view of the session.  Elevating adds these tokens to the program that has been elevated.

    Clearly and correctly understanding this has broad implications for understanding what is happening and how to use this capability.  Even elevated an "admin" may not have all security access.  Some "admin" accounts may have to ability to add other tokens.  This will be visible in the session security.

    To find currently enabled privileges use the following command:

    whoami /priv

    Non elevated results for BUILTIN/Administrators group on a non-domain workstation:

    PS C:\scripts> whoami /priv
    
    PRIVILEGES INFORMATION
    ----------------------
    
    Privilege Name                Description                          State
    ============================= ==================================== ========
    SeShutdownPrivilege           Shut down the system                 Disabled
    SeChangeNotifyPrivilege       Bypass traverse checking             Enabled
    SeUndockPrivilege             Remove computer from docking station Disabled
    SeIncreaseWorkingSetPrivilege Increase a process working set       Disabled
    SeTimeZonePrivilege           Change the time zone                 Disabled
    PS C:\scripts>


    Elevated results for BUILTIN/Administrators group on a non-domain workstation:

    PS C:\scripts> whoami /priv
    
    PRIVILEGES INFORMATION
    ----------------------
    
    Privilege Name                  Description                               State
    =============================== ========================================= ========
    SeIncreaseQuotaPrivilege        Adjust memory quotas for a process        Disabled
    SeSecurityPrivilege             Manage auditing and security log          Disabled
    SeTakeOwnershipPrivilege        Take ownership of files or other objects  Disabled
    SeLoadDriverPrivilege           Load and unload device drivers            Disabled
    SeSystemProfilePrivilege        Profile system performance                Disabled
    SeSystemtimePrivilege           Change the system time                    Disabled
    SeProfileSingleProcessPrivilege Profile single process                    Disabled
    SeIncreaseBasePriorityPrivilege Increase scheduling priority              Disabled
    SeCreatePagefilePrivilege       Create a pagefile                         Disabled
    SeBackupPrivilege               Back up files and directories             Disabled
    SeRestorePrivilege              Restore files and directories             Disabled
    SeShutdownPrivilege             Shut down the system                      Disabled
    SeDebugPrivilege                Debug programs                            Enabled
    SeSystemEnvironmentPrivilege    Modify firmware environment values        Disabled
    SeChangeNotifyPrivilege         Bypass traverse checking                  Enabled
    SeRemoteShutdownPrivilege       Force shutdown from a remote system       Disabled
    SeUndockPrivilege               Remove computer from docking station      Disabled
    SeManageVolumePrivilege         Perform volume maintenance tasks          Disabled
    SeImpersonatePrivilege          Impersonate a client after authentication Enabled
    SeCreateGlobalPrivilege         Create global objects                     Enabled
    SeIncreaseWorkingSetPrivilege   Increase a process working set            Disabled
    SeTimeZonePrivilege             Change the time zone                      Disabled
    SeCreateSymbolicLinkPrivilege   Create symbolic links                     Disabled
    PS C:\scripts>

    Privileges marked as disabled can be programmatically enabled.  Missing privileges can only be added by an elevated Admin with correct privileges.


    \_(ツ)_/

    Tuesday, July 7, 2020 7:49 PM
    Moderator
  • Hi,
    If you are willing to use two different files for username & password and store username in plain text, you can use something like this

    $credential = Get-Credential
    $credential.Password | ConvertFrom-SecureString | Set-Content "D:\User_Folders\Desktop\encrypted_password.txt"
    $credential.username | Set-Content "D:\User_Folders\Desktop\Username.txt"

    $user = cat D:\User_Folders\Desktop\Username.txt
    $pass=cat D:\User_Folders\Desktop\encrypted_password.txt | Convertto-securestring

    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user, $pass

    New-PSDrive -name "Drive Letter" -PSProvider FileSystem -Root \\FileShare -Credential $cred -persist

    Regards
    Rav

    Tuesday, July 7, 2020 9:33 PM
  • Hi,
    If you are willing to use two different files for username & password and store username in plain text, you can use something like this

    $credential = Get-Credential
    $credential.Password | ConvertFrom-SecureString | Set-Content "D:\User_Folders\Desktop\encrypted_password.txt"
    $credential.username | Set-Content "D:\User_Folders\Desktop\Username.txt"

    $user = cat D:\User_Folders\Desktop\Username.txt
    $pass=cat D:\User_Folders\Desktop\encrypted_password.txt | Convertto-securestring

    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user, $pass

    New-PSDrive -name "Drive Letter" -PSProvider FileSystem -Root \\FileShare -Credential $cred -persist

    Regards
    Rav

    Simple question.  Why would you want to use two files when one does everything in one line?


    \_(ツ)_/

    Tuesday, July 7, 2020 9:58 PM
    Moderator
  • Thank you for your suggestion. I will use -Persist.
    Wednesday, July 8, 2020 7:58 PM
  • -Persist worked for me.

    What does -Scope Global do?

    I need my script to run on boot and start WSUS Offline Updates until all updates are installed.

    Since "Reboot and Recall" function does not work in the latest Windows 10 builds, users need to reboot themselves. My script will make it easier for them by starting updates automatically.

    So, script will run on boot (Autorun.bat will be placed in Startup folder).

    If I use

    New-PSDrive -Name "Z" -Root "\\SITServer\SITData\PC Setup" -Persist -PSProvider "FileSystem" -Credential $credential
    Net Use

    Will it keep network drive mapped after reboot? If so, how do I just log into it without mapping it again?

    Or do I need to disconnect from Z drive every time before mapping it again?

    Thank you very much

    Wednesday, July 8, 2020 8:05 PM
  • The credentials are used to create the mapping. The permissions on the share, directory, or file limit the access.

    If you use -Persist there's no need to recreate the mapping unless you've removed it.

    The -Scope, in this case, is probably superfluous. It's not hurting anything, though. Without -Persist, the -Scope defines from where the new mapping can be referenced. It's not specific to the cmdlet, though -- all object have a scope. If you create an object on a code block, it's available in the code block. If you create a variable in a script, it's available until the script ends. If you create a variable and declare it to have a global scope it available in the PowerShell session.

    help about_scope


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Wednesday, July 8, 2020 9:51 PM
  • Thank you very much!
    Thursday, July 9, 2020 2:39 PM