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

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

我有一个批处理文件,它接受拖放到它上面的文件(通常是多个文件)的路径参数。然后它将这些传递给 PowerShell 脚本。

但是,当有人从正在通过其 UNC 路径名访问的文件夹中删除文件时,它会 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.

如何将参数中每个文件名的 \server.com\shared data\ 替换为 Q:\?我的 PowerShell 脚本执行所有处理,所以我想在它被发送到 PowerShell 之前修复它。

我明白了我可以运行'cls'在批处理的开头清除警告。

对于这种情况,我无法修改注册表。

@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%'"

所以,我希望有一种方法可以防止 .ps1 PowerShell 脚本看到任何 \server.com\shared data\,而是让它看到 Q:\

现在不能尝试,但我想你可以尝试其中之一:

  • 获取所有参数的名称并将 \server.com\ 解析为 Q:\,这可能不是最好的主意,因为每个用户可能有不同的单位字母
  • 如果文件与脚本位于同一目录(或始终位于同一源文件夹),请尝试使用 pushd \server.com\shared... 将目录映射到临时单元,然后使用 cd 将其获取到用它。完成后,使用 popd 取消映射文件夹(这将取消映射最后一个映射单元)

这就是我最终使用的:启用延迟扩展是票。

@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%'"