Patrick
Patrick

Reputation: 265

NET USE only works once in powershell

My requirement is to connect to a remote computer, copy files with the extension of .TRA to a different remote computer.

Now my difficulty arises in that the source machine aren't on the domain so I need to connect with alternate credentials.

My first sticking point is trying to use New-PSDrive. It doesn't appear to allow me to pass stored credentials. I have tried various versions of this:

$cred = Get-Credential
New-PSDrive -NAME Z: -PSprovider Filesystem -root \\Computer\Exchange -credentials $cred

and I get an error

The provider does not support the use of credentials. Perform the operation again without specifying credentials.

This appears to be a bug (see halr9000's comment here : Connecting to a network folder with username/password in Powershell)

My alternative was to use NET USE, which works fine but only once.

In the full script below I map to 8 different machines. The first of these works. After that any attempt to use NET USE (or New-Object WScript.NETWORK, mentioned as a work around on the Technet article linked above) fails. Or rather it doesn't fail.

Its creates a mapped drive, which I can see if I type NET USE, or if I look in explorer (and its browsable). But I cannot connect to that drive in Powershell. Its like it doesn't exist, Test-Path Z: returns False. Right up until I run NET USE Z: /D which successfully deletes the drive.

Can someone please help me with one or other of my issues please? Don't make me do this in DOS!

Full script :

$int = 0
$arrStagePC = "BOX42", "BOX43", "BOX44", "BOX45", "BOX46", "BOX47", "BOX48", "BOX49" 
$arrData = "0848","5144","5292","5383","2158","2646","0061","2331"
Foreach($strComp in $arrStagePC)
    {
    $arr = $arrData[$int]
    $comp = $strComp
    net use z: \\$arr\Exchange /user:admin password
    Copy-Item z:\*$date.tra \\$comp\Export$
    net use z: /d
    $int++
    }

EDIT Have a look at @Christians accepted answer below. I didn't actually need to Get-Content that folder, I just needed to copy data from the source so the bit of the script doing the business on there now looks like :

Foreach($strComp in $arrStagePC)
        {
        $arr = $arrData[$int]
        $comp = $strComp
        net use z: \\$arr\Exchange /user:admin password
        Copy-Item FILESYSTEM::Z:\*.TRA \\$comp\Export$
        net use z: /d
        $int++
        }

Upvotes: 3

Views: 21511

Answers (3)

Claus
Claus

Reputation: 51

Had same issue. Mended mine by adding *New-PSDrive z FileSystem z:* after the NET USE. Seems like NET USE /DELETE disturbs the PS housekeeping.

Upvotes: 5

CB.
CB.

Reputation: 60928

Using NET USE try access in this way:

 Set-Location  FILESYSTEM::Z:

Upvotes: 7

David Brabant
David Brabant

Reputation: 43499

Try this, maybe:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("Z:", "\\$arr\Exchange", $false, "admin", "password")

Upvotes: 1

Related Questions