Powershell: how to connect to a network folder in another domain with a saved username / password without a name

I am trying to connect to a network resource through powershell. The network share is in a different domain, so I need to provide credentials. Since New-PSDrive does not support credentials, I was going to use net use , but I am worried about providing my username and password directly in the text in the script. I made ConvertTo-SecureString make a secure string from my password, then use ConvertFrom-SecureString and save the result in a file. Then I pulled it from a file like this, and tried using net :

$password = Get-Content <locationOfStoredPasswordFile> | ConvertTo-SecureString
net use q: "\\server\share" $password /user:domain\username

But net use does not recognize the protected string.

Does anyone have any ideas on how to store credentials, so using a network can use them? Thank!

+5
source share
1 answer

Here are two functions that I use to encrypt / decrypt strings. They were adapted from powershell.com article, but I have no link. The idea is that your password file will save the output of Protect-String, and then convert it back to a regular string, read the file and call UnProtect-String, this value returned from the UnProtect string will be your $ password variable.

#######################
function Protect-String 
{
    param([string]$InputString)
    $secure = ConvertTo-SecureString $InputString -asPlainText -force
    $export = $secure | ConvertFrom-SecureString
    write-output $export

} #Protect-String

#######################
function UnProtect-String 
{
    param([string]$InputString)

    $secure = ConvertTo-SecureString $InputString
    $helper = New-Object system.Management.Automation.PSCredential("SQLPSX", $secure)
    $plain = $helper.GetNetworkCredential().Password
    write-output $plain

} #UnProtect-String
+7
source

All Articles