Travis Bennett
Travis Bennett

Reputation: 143

In Win10 Batch File's Arguments: Replacing UNC Path Names' prefixes with known mapped drive

I have a batch file that takes an argument of the paths of file(s) (usually multiple files) dropped onto it. It then passes those to a PowerShell script.

However, when someone drops files from a folder being access from its UNC path name, it barfs:

'\\server.com\shared data\Folder\Subfolder\Etc'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.

How can I replace \\server.com\shared data\ with Q:\ for every filename in the argument? My PowerShell script does all the processing, so I want to fix it before it ever gets sent into PowerShell.

I get I can run 'cls' at the beginning of the beginning of the batch to clear away the warning.

I cannot modify the registry for this case.

@echo off
Title Pass arguments from this Batch script to PowerShell script of same name
rem 
rem Batch Handler of Command Line Arguments for Microsoft Windows
rem Enables Passing Command Line Arguments to PowerShell Script
rem   
rem The name of the script is drive path name of the Parameter %0
rem     (= the batch file) but with the extension ".ps1"
set PSScript=%~dpn0.ps1
set args=%1

:More
shift
if '%1'=='' goto Done
set args=%args%, %1
goto More
:Done
powershell.exe -NoExit -Command "& '%PSScript%' '%args%'"

So, I'm hoping there is a way to keep the .ps1 PowerShell script from seeing any \\server.com\shared data\ and just let it see Q:\ instead.

Upvotes: 0

Views: 3136

Answers (2)

Travis Bennett
Travis Bennett

Reputation: 143

This is what I ended up using: Enable Delayed Expansion was the ticket.

@echo off
setlocal enableDelayedExpansion
Title Sample Title (Initializing...)
rem 
rem Batch Handler of Command Line Arguments for Microsoft Windows
rem  Enables Passing Command Line Arguments to PowerShell Script
rem
rem 
rem The name of the script is drive path name of the Parameter %0
rem     (= the batch file) but with the extension ".ps1"
set "PSScript=%~dpn0.ps1"
set "args=%1"

:More
shift
if '%1'=='' goto Done
set "args=%args%, %1"
goto More

:Done
set "args=!args:\\server.com\shared data\=Q:\!"
if /i "!args!" == "\\server.com\shared data\=Q:\" ( set "args=" )
powershell.exe -NoExit -Command "& '%PSScript%' '%args%'"

Upvotes: 1

JaviL
JaviL

Reputation: 102

Can’t try it right now, but I think you can try one of these:

  • Get all arguments’ names and parse \server.com\ to Q:\, not probably the best idea as each user could have different unit letter
  • If the files are on the same directory as the script (or always on same origin folder) try using pushd \\server.com\shared... to map the directory to a temp unit and then get it with cd to use it. When you are done, unmap the folder with popd (this will unmap last mapped unit)

Upvotes: 0

Related Questions