如何在命令文件中的 -file 中使用“.\”

How to use ".\" in -file in a command file

我需要通过机器 A 上的 Powershell 脚本 (A.ps1) 在机器 B 上执行命令文件 (B.cmd)。我不想静态指定路径

B.cmd 应该执行与 B.cmd

在同一文件夹中的 C.ps1

机器 A:A.ps1
机器 B:B.cmd,C.ps1(都在同一文件夹中)

所以我的命令文件看起来像这样B.cmd

@echo off
powershell.exe -file ".\C.ps1" -Iterations 10
echo
echo
pause

我从中调用 B.cmd 文件的 A.ps1 文件中出现错误

A.ps1

Invoke-Command -ComputerName $systemName -credential $credentials -ScriptBlock {Invoke-Expression -Command: "cmd.exe /c C:\Temp\Batch\Test\B.cmd"}

A.ps1 抛出错误:

**The argument '.\C.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.**
+ CategoryInfo          : NotSpecified: (The argument '....File parameter.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName        : XXX

我如何使 .\ 工作或者是否有替代方法或者使用 .\ 进行远程执行是否错误?

请原谅我的无知,因为我对 PS 非常陌生,谢谢!

如果您能够更改 ABC.cmd 您可以使用以下内容

powershell.exe -file "%~dp0\XYZ.ps1"

这将从中获取 ABC.cmd 脚本 运行 的文件夹。请注意,%~dp0 无法在 cmd 中进行测试,您需要从脚本中对其进行测试。

所以不要用批处理文件包装它。浪费时间和混淆问题。

invoke-command -comp $computername -filepath C:\Temp\Batch\Test\XYZ.ps1 

如果您需要 运行 某项操作 10 次,请在 PS 脚本中循环执行。