Search code examples
powershellvariablescredentialsnet-usedrive-mapping

PowerShell - net use doesn't work - issue with variables


I want to map a network resource remotely via net use.

This is my PowerShell code:

$user = Read-Host -Prompt "Enter Username"
$pw = Read-Host -Prompt "Enter Password" -AsSecureString
net use X: \\Server\dir1\dir2 /persistent:no /user:$user $pw

It works if I write my credentials instead of the variables.

But I need to read in the credentials.

Is there a way to use variables in the net use command?


Solution

  • As PetSerAl answered in a comment, you can remove -AsSecureString, but a better approach might be offering the security/niceness of getting the password in a secure manner (doesn't reveal password characters as you type), and only decrypting it when you need it for your variable.

    $pw = Read-Host -Prompt "Enter Password" -AsSecureString
    
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw)
    $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
    
    Write-Output "UnsecurePassword is: $UnsecurePassword"
    

    Note: answer adapted from: Convert a secure string to plain text