好的东西这么简单只是不适合我.我有一个接受单个参数的cmdlet.我试图在Windows批处理文件中调用cmdlet.批处理文件包含:
cd %SystemRoot%\system32\WindowsPowerShell\v1.0
powershell Set-ExecutionPolicy Unrestricted
powershell 'C:\convert-utf8-to-utf16.ps1 C:\test.txt'
powershell Set-ExecutionPolicy Restricted
pause
Run Code Online (Sandbox Code Playgroud)
我的ps1文件再没有做任何特别的事:
function convert-utf8-to-utf16 {
$tempfile = "C:\temp.txt"
set-ExecutionPolicy Unrestricted
get-content -Path $args[0] -encoding utf8 | out-file $tempfile -encoding Unicode
set-ExecutionPolicy Restricted
}
Run Code Online (Sandbox Code Playgroud)
当我执行bat文件时,它只是运行完成(没有错误消息),它似乎没有创建temp.txt文件.
我可以在PS命令提示符下运行powershell命令文件,但不能在cmd中运行!
任何人有任何想法可能是错的?
谢谢
Nat*_*ley 22
从Powershell版本2开始,您可以像这样运行Powershell脚本......
powershell -ExecutionPolicy RemoteSigned -File "C:\Path\Script.ps1" "Parameter with spaces" Parameter2
Run Code Online (Sandbox Code Playgroud)
现在,如果我只能找到一种方法来处理拖放文件到Powershell脚本.
我解释了为什么要从批处理文件中调用PowerShell脚本以及如何在我的博客文章中执行此操作.
这基本上就是你要找的东西:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\convert-utf8-to-utf16.ps1' 'C:\test.txt'"
Run Code Online (Sandbox Code Playgroud)
如果您需要以管理员身份运行PowerShell脚本,请使用以下命令:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\convert-utf8-to-utf16.ps1"" ""C:\test.txt""' -Verb RunAs}"
Run Code Online (Sandbox Code Playgroud)
虽然不是硬编码PowerShell脚本的整个路径,但我建议将批处理文件和PowerShell脚本文件放在同一目录中,正如我的博客文章所描述的那样.
问题出在ps1文件中 - 你声明了一个函数,但你没有调用它.我会像这样修改它:
param($path)
function convert-utf8-to-utf16 {
$tempfile = "C:\temp.txt"
set-ExecutionPolicy Unrestricted
get-content -Path $args[0] -encoding utf8 | out-file $tempfile -encoding Unicode
set-ExecutionPolicy Restricted
}
convert-utf8-to-utf16 $path
Run Code Online (Sandbox Code Playgroud)
它会工作.但是,它不是必需的,您可以简单地省略函数声明并将正文移动到脚本本身:
param($path)
$tempfile = "C:\temp.txt"
set-ExecutionPolicy Unrestricted
get-content -Path $path -encoding utf8 | out-file $tempfile -encoding Unicode
set-ExecutionPolicy Restricted
Run Code Online (Sandbox Code Playgroud)
尝试使用以下语法:
cd %SystemRoot%\system32\WindowsPowerShell\v1.0
powershell {Set-ExecutionPolicy Unrestricted}
powershell "& C:\convert-utf8-to-utf16.ps1 C:\test.txt"
powershell {Set-ExecutionPolicy Restricted}
pause
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69517 次 |
| 最近记录: |