簡體   English   中英

運行批處理命令時路徑無效

[英]invalid path when running a batch command

我有一個批處理腳本,它可以進行很多審核。 我運行該腳本的文件夾位於我的桌面上,登錄的用戶名是“ Doctor A”(命令運行的路徑是c:\\user\\Doctor a\\Desktop\\script\\test.bat )。

在運行som批處理命令后,我嘗試使用以下行啟動PowerShell腳本:

powershell.exe -ExecutionPolicy Bypass "%~dp0\Audit_folders_and_regkeys.ps1"

當我運行此命令時,出現錯誤提示

The term 'C:\Users\Doctor' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:16
+ C:\Users\Doctor <<<<  A\Desktop\CyperPilot_Audit_Conf_External_Network\CyperPilot_Audit_Conf_External_Network\\Audit_folders_and_regkeys.ps1
     + CategoryInfo          : ObjectNotFound: (C:\Users\Doctor:String) [], CommandNotFoundException
     + FullyQualifiedErrorId : CommandNotFoundException

看來它不會比C:\\Users\\Doctor更進一步,我如何在批處理文件中寫入以解決此問題?

當您以某種方式運行PowerShell時(與使用-Command基本相同),雙引號字符串的內容被解釋為PowerShell語句(或PowerShell語句列表)。 基本上是這樣的:

  1. 您輸入命令:

     powershell.exe -ExecutionPolicy Bypass "%~dp0\\Audit_folders_and_regkeys.ps1" 
  2. CMD擴展位置參數%~dp0

     powershell.exe -ExecutionPolicy Bypass "c:\\user\\Doctor a\\Desktop\\script\\Audit_folders_and_regkeys.ps1" 
  3. CMD啟動powershell.exe並將命令字符串傳遞給它(注意已刪除的雙引號):

     c:\\user\\Doctor a\\Desktop\\script\\Audit_folders_and_regkeys.ps1 
  4. PowerShell看到不帶雙引號的語句,並嘗試執行帶有參數a\\Desktop\\script\\Audit_folders_and_regkeys.ps1的(不存在)命令c:\\user\\Doctor

處理這個問題的最佳方法是使用參數-File ,如@PetSerAl在評論中建議:

powershell.exe -ExecutionPolicy Bypass -File "%~dp0\Audit_folders_and_regkeys.ps1"

否則,您必須在命令字符串中放入嵌套的引號,以補償在傳遞參數時刪除的引號:

powershell.exe -ExecutionPolicy Bypass "& '%~dp0\Audit_folders_and_regkeys.ps1'"

請注意,在這種情況下,您還需要使用調用運算符( & ),否則PowerShell將僅回顯路徑字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM