无法处理参数转换 [英] Cannot process argument transformation

查看:16
本文介绍了无法处理参数转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

受此post启发,我创建了以下脚本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

但是,在执行时,它返回以下错误:

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

我已经搜索了这个错误,但找不到。在我看来,它无法正确转换字符串类型!请帮帮忙!

推荐答案

您的最佳选择是在PowerShellV3或更高版本中使用--%。请看我使用--%写的blog post。在V1/V2中,情况非常糟糕,您可以在Connect bug on the issue中看到。V1/V2中的常见解决方法是使用Start-Process或.NET的Process.Start。从这些变通方法列表中,我有点喜欢这个:

[System.Diagnostics.Process]::Start("Cmd", "/c anything you want to put here with embedded quotes, and variables")

这实际上就是--%对它后面的所有参数进行的解析,即它以类似于cmd.exe参数解析的简化模式解析它们,包括用%envVarName%引用的扩展环境变量。

这篇关于无法处理参数转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆