Timo
Timo

Reputation: 9845

Cmd doesn't pass arguments to powershell script

I have a powershell script that I want to run from the command line (cmd, not powershell):

powershell.exe -NoLogo -NoProfile -ExecutionPolicy ByPass -File "MyScript.ps1" -ScriptParam1 2020 -ScriptParam2 "bla" -ScriptParam3 "blub"

When I paste this code in powershell everything works fine but when I paste it in cmd, powershell starts and prompts me for the script parameters because they're mandatory. Why are those arguments not recognized in cmd?

Here is the content of MyScript

[CmdletBinding()]
param (
    [Parameter(Mandatory)]
    [int] $ScriptParam1,

    [Parameter(Mandatory)]
    [string] $ScriptParam2,

    [Parameter(Mandatory)]
    [string] $ScriptParam3
)

$PSVersionTable

Upvotes: 0

Views: 727

Answers (1)

postanote
postanote

Reputation: 16126

Because they are outside command request, meaning, your script call.

Try it this way...

# Contents of hello.ps1
Get-Content -Path 'D:\Scripts\hello.ps1'
# Results
<#
[CmdletBinding(SupportsShouldProcess)]

Param
(
    [Parameter(ParameterSetName="Domain",Mandatory=$true)]
    [string]$ScriptParam1,
    [Parameter(ParameterSetName="Domain",Mandatory=$true)]
    [string]$ScriptParam2,
    [Parameter(ParameterSetName="Domain",Mandatory=$true)]
    [string]$ScriptParam3
)



$host
$PSversionTable
Write-Host 'Hello World'
Get-Date
#>
powershell.exe -NoExit -NoLogo -NoProfile -ExecutionPolicy ByPass "D:\Scripts\hello.ps1 -ScriptParam1 param1 -ScriptParam2 param2 -ScriptParam3 param3"
# Results
<#
Name             : ConsoleHost
Version          : 5.1.19041.1
...

Key   : PSVersion
Value : 5.1.19041.1
...

Hello World
...
#>

powershell.exe -NoExit -NoLogo -NoProfile -ExecutionPolicy ByPass "D:\Scripts\hello.ps1 -ScriptParam1 param1 -ScriptParam2 param2 -ScriptParam3 param3"
# Results
<#
C:\>ver

Microsoft Windows [Version 10.0.19041.388]

C:\>powershell.exe -NoExit -NoLogo -NoProfile -ExecutionPolicy ByPass "D:\Scripts\hello.ps1 -ScriptParam1 param1 -ScriptParam2 param2 -ScriptParam3 param3"


Name             : ConsoleHost
Version          : 5.1.19041.1
...

Key   : PSVersion
Value : 5.1.19041.1
...

Hello World
...


C:\>ver

Microsoft Windows [Version 10.0.19041.388]

C:\>powershell.exe -NoExit -NoLogo -NoProfile -ExecutionPolicy ByPass "D:\Scripts\hello.ps1"

cmdlet hello.ps1 at command pipeline position 1
Supply values for the following parameters:
ScriptParam1: 1
ScriptParam2: 2
ScriptParam3: 3


Name             : ConsoleHost
Version          : 5.1.19041.1
...

Key   : PSVersion
Value : 5.1.19041.1
...

Hello World
...
#>

Parsing happens a bit differently when you are already in a PowerShell instance than when you are starting one from cmd.exe. Cmd.exe and to read it all first, and cmd.exe has no idea what those -ScriptParam* are, thus they are ignored.

As per the example shown.

Upvotes: 1

Related Questions