Home > Net >  Migrating scripts using "net use" to PowerShell' "New-PSDrive"
Migrating scripts using "net use" to PowerShell' "New-PSDrive"

Time:01-30

I have some scripts that copy files between a local system and a few shares. These scripts use net use to manage their connections. Since net use doesn't allow mutliple connections I have to be careful to execute these scripts in order so that they don't throw any exception.

Recently I've found that PowerShell's New-PSDrive would create a temporary connection in the context of a PowerShell script:

Creates temporary and persistent drives that are associated with a location in an item data store.

Temporary drives exist only in the current PowerShell session and in sessions that you create in the current session.

Based on this description would it be correct to assume that with PowerShell I could execute multiple scripts at the same time and they all would be able to connect to multiple shares without errors and automatically disconnect when the script ends?

CodePudding user response:

You are correct that using PowerShell's New-PSDrive cmdlet would allow you to create temporary connections in the context of a PowerShell script, which would be separate from the connections created by other scripts. This would allow you to execute multiple scripts simultaneously without them interfering with each other's connections.

Additionally, the temporary drives created by New-PSDrive will automatically disconnect when the script ends, or when the PowerShell session closes. This will help avoid issues with lingering or orphaned connections that can occur when using net use.

Actually, if you need a connection to persist the connection beyond the current PowerShell session, you can create a persistent drive using the -Persist option. You may need to provide credentials if the share is on a remote server though.

Incredibly, -Persist must be combined with -Global in order to establish persistent connections from a script. Even more incredibly, it was decided not to fix this glaring usability problem. See GitHub issue #15752mklement0

Therefore, using PowerShell's New-PSDrive cmdlet instead of net use to manage your connections would enable you to execute multiple scripts simultaneously, connect to multiple shares without errors, and automatically disconnect when the script ends.

Supporting Resources

  • Related