Unable to process argument conversion

Inspired by this post, I created a script below 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

However, when executed, it returns this error:

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

I was looking for this error, but I can not understand. It seems to me that it cannot correctly convert the string type! Please, help!

+3
source share
2 answers

--% PowerShell V3 . . --%. V1/V2 , . 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, env vars, %envVarName%.

+3

, , :

Function Invoke-DOSCommands {
    Param(
        [Parameter(Position=0,Mandatory=$true)]
        [String]$cmd)

    $comspec =  $env:comspec # have to get comspec
    $cwd = Get-Location # ensure correct working directory
    $pstartinfo = new-object -type System.Diagnostics.processStartInfo -Argumentlist "$comspec","/c $cmd"
    $pstartinfo.WorkingDirectory= $cwd
    Write-Debug "cmd: $pstartinfo.FileName"
    Write-Debug "args: $pstartinfo.Arguments"
    Write-Debug "dir: $pstartinfo.WorkingDirectory"
    #[System.Diagnostics.Process]::Start("Cmd", "/c $cmd")
    [System.Diagnostics.Process]::Start($pstartinfo)
}

Invoke-DOSCommands "Echo ""Hello World"" & dir & pause" # testing function 
+1

Source: https://habr.com/ru/post/1737718/


All Articles