能否用变量/函数替代常量字符串作为PowerShell -File参数?
问题描述
能不能用变量或函数形式的powershell -File $file,替代常量字符串形式的powershell -File 'C:\Script\test.ps1'来传递File参数?
以下命令能正常运行:
C:\Script>PowerShell.exe -ExecutionPolicy Bypass -windowstyle hidden "$file = Get-ChildItem -Path C:\Script -Include test.ps1 -Recurse | Select-Object -ExpandProperty FullName"; Invoke-Item $file
但把Invoke-Item换成-File后,命令执行失败并报错:
执行的命令:
C:\Script>PowerShell.exe -ExecutionPolicy Bypass -windowstyle hidden "$file = Get-ChildItem -Path C:\Script -Include test.ps1 -Recurse | Select-Object -ExpandProperty FullName"; -File $file
错误信息:
-File : 无法将术语“-File”识别为 cmdlet、函数、可执行程序或脚本文件的名称。请检查名称的拼写,或者如果路径包含在内,请验证路径是否正确,然后重试。 所在位置 行:1 字符:115 + ... st.ps1 -Recurse | Select-Object -ExpandProperty FullName; -File $file + ~~~~~ + CategoryInfo : ObjectNotFound: (-File:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
问题根源
你写错了参数的作用位置:-File是powershell.exe的启动参数,必须紧跟在powershell.exe命令之后,不能单独作为会话内的命令执行。你原来的命令里,; -File $file这部分是在当前PowerShell会话里执行的,系统自然会把-File当成未知命令报错。
正确实现方式
1. 单进程内执行脚本(推荐)
不用额外启动新的PowerShell进程,直接在同一个启动命令里找到脚本路径并执行:
C:\Script>PowerShell.exe -ExecutionPolicy Bypass -windowstyle hidden -Command "$file = Get-ChildItem -Path C:\Script -Include test.ps1 -Recurse | Select-Object -ExpandProperty FullName; & $file"
这里的&是PowerShell的调用操作符,用来执行变量指向的脚本文件路径。
2. 启动新进程执行脚本(如果需要独立进程)
如果必须通过新的powershell.exe进程执行脚本,需要把变量逻辑和启动命令整合到-Command参数里:
C:\Script>PowerShell.exe -ExecutionPolicy Bypass -windowstyle hidden -Command "$file = Get-ChildItem -Path C:\Script -Include test.ps1 -Recurse | Select-Object -ExpandProperty FullName; PowerShell.exe -File $file"
3. 直接传递动态路径(简化写法)
如果能确保查找结果只有一个脚本文件,可以直接把路径查询结果作为-File的参数:
C:\Script>PowerShell.exe -ExecutionPolicy Bypass -windowstyle hidden -File (Get-ChildItem -Path C:\Script -Include test.ps1 -Recurse | Select-Object -ExpandProperty FullName)
注:如果是在CMD环境下执行,需要调整引号格式,改用-Command参数包裹逻辑。
内容的提问来源于stack exchange,提问作者FCF75
相关产品推荐
相关产品推荐

