Vij*_*jay 5 powershell powershell-2.0
受这篇文章的启发,我在下面创建了脚本DOSCommands.ps1
Function Invoke-DOSCommands {
Param(
[Parameter(Position=0,Mandatory=$true)]
[String]$cmd,
[String]$tmpname = $(([string](Get-Random -Minimum 10000 -Maximum 99999999)) + ".cmd"),
[switch]$tmpdir = $true)
if ($tmpdir) {
$cmdpath = $(Join-Path -Path $env:TEMP -ChildPath $tmpname);
}
else {
$cmdpath = ".\" + $tmpname
}
Write-Debug "tmpfile: " + $cmdpath
Write-Debug "cmd: " + $cmd
echo $cmd | Out-File -FilePath $cmdpath -Encoding ascii;
& cmd.exe /c $cmdpath | Out-Null
}
Invoke-DOSCommands "Echo ""Hello World""", -tmpdir $false
Run Code Online (Sandbox Code Playgroud)
但是,在执行时会返回此错误:
Invoke-DOSCommands : Cannot process argument transformation on parameter 'cmd'. Cannot convert value to type S ystem.String.
At DOSCommands.ps1:20 char:19
+ Invoke-DOSCommands <<<< "Echo ""Hello World""", -tmpdir $false
+ CategoryInfo : InvalidData: (:) [Invoke-DOSCommands], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Invoke-DOSCommands
Run Code Online (Sandbox Code Playgroud)
我已经搜索了此错误,但无法解决。在我看来,它不能正确转换字符串类型!请帮忙!
最好的选择是在 PowerShell V3 或更高版本中使用--%
。请参阅我写的关于使用的博客文章--%
。在 V1/V2 中,情况很糟糕,正如您在该问题的 Connect bug中看到的那样。V1/V2 中常见的解决方法是使用 Start-Process 或 .NET 的 Process.Start。从这些解决方法列表中,我有点喜欢这个:
[System.Diagnostics.Process]::Start("Cmd", "/c anything you want to put here with embedded quotes, and variables")
Run Code Online (Sandbox Code Playgroud)
这实际上是--%
对其后面的所有参数的解析的作用,即它以类似于 cmd.exe 参数解析的简化模式解析它们,包括扩展%envVarName%
.
归档时间: |
|
查看次数: |
13511 次 |
最近记录: |