2016-03-21 36 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只会回显路径字符串。