Remotely setting network credentials using cmdkey

I have a task to automate the build on Azure VM with custom extension scripts. One of the tasks of the custom extension scripts is to map network drives [and save its credentials]. The custom extension scripts are automatically executed by Azure using the ADMIN user id. This causes problems as the mapped network drive resides in a different user domain. As a consequence, I have to create another script [map.ps1] which does the mapping and have it invoked from a wrapper script [deploy.ps1].

Please note snippets of my script:


$storageCred=”A long string of name value pairs containing the network user id and password”
$domainAdminUserId = “xxxx/yyyy”
$domainAdminPassword = ( ‘zzzz’ | ConvertTo-SecureString -AsPlainText -Force )
$domainAdminCredentials = New-Object -typename System.Management.Automation.PSCredential -argumentlist $domainAdminUserId, $domainAdminPassword

Enable-PSRemoting -Force
Invoke-Command -ComputerName localhost -FilePath “C:\FTPFiles\map.ps1” -Credential $domainAdminCredentials -ArgumentList $storageCred -Verbose


$storageCredArray = $storageCred.Split(‘~’)
$storageCredLookupTable = ConvertFrom-StringData ($storageCredArray | out-string)

Write-Host ‘Mapping file shares – started’ -ForegroundColor Green
$driveLetterAscii = [Byte][char]’X’

foreach ($usr in $storageCredLookupTable.Keys) {
$driveLetter = [Char][byte]$driveLetterAscii
CMDKEY /add:$ /user:$env:COMPUTERNAME\$usr /pass:($storageCredLookupTable.Item($usr))
Net Use ($driveLetter + “:”) “\\$\share” /SAVECRED /PERSISTENT:YES
if (Test-Path ($driveLetter + “:\Interfaces”)) {
Write-Host “$driveLetter mapped to $\share successfully” -ForegroundColor Green
} else {
Write-Host “Failure in mapping $driveLetter to $\share” -ForegroundColor Red

When I run this, it errors while adding the network credentials [cmdkey /add]. I get the following error:

CMDKEY: Credentials cannot be saved from this logon session

Any help on this is much appreciated.

That’s a limitation of the Cmdkey command – not really a PowerShell thing. But it’s related to the way Remotig handles credentials. The remote session doesn’t actually get a credential, it gets a delegated ticket, so there’s no token to actually save. That’s all by design, and not something you can reconfigure.


This entry was posted in develop and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s