在 Win10 批处理文件的参数中:将 UNC 路径名的前缀替换为已知的映射驱动器


  • 我在服务器上的共享云端硬盘中工作。
  • 有时人们使用其映射的驱动器,Q:FolderSubfolderEtc
  • 其他时候人们使用它的UNC路径:\server.comshared dataFolderSubfolderEtc

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

但是,当有人从从其 UNC 路径名访问的文件夹中删除文件时,它会阻止:

'\server.comshared dataFolderSubfolderEtc'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.

如何将参数中的每个文件名\server.comshared 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.comshared data,而只是让它看到Q:

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

@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.comshared data=Q:!"
if /i "!args!" == "\server.comshared data=Q:" ( set "args=" )
powershell.exe -NoExit -Command "& '%PSScript%' '%args%'"

现在不能尝试,但我认为您可以尝试以下之一:

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

最新更新