2016-03-21 35 views
1

我有一個批處理腳本,它啓用了大量的審計。從我運行此腳本的文件夾放置在我的桌面上,登錄的用戶名是「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更進一步我在批處理文件中寫什麼來解決這個問題?

+0

如果我把該腳本文件夾放在c:\ script \ ....中,它就完美了 –

+4

'powershell.exe -ExecutionPolicy Bypass -File「%〜dp0 \ Audit_folders_and_regkeys.ps1」' – PetSerAl

回答

2

當您按照您的方式運行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'" 

注意,在這種情況下,你還需要使用調用運算符(&),OTH erwise PowerShell只會回顯路徑字符串。