none
Behavior of array of commands. RRS feed

  • Question

  • Hi Everyone,

    I've been playing around today in creating an array to call my functions in a build order, and I'm running into a bit of strangeness.  Example :

    function Main{
    $commands = @("Mount-MDT", "Validate-Media -media $media", "Create-MDTUSB", "Copy-Refresh", "Copy-Wipe", "Copy-Diskpart", "Create-MDTMedia")
    
    $I=0
    
         foreach($c in $commands){
    
         $i+=[decimal]::round(100 / $commands.count)
         if($i -gt 100){$i = 100}
    
         Write-Output "Progress: $I%"
         &$c
    
         }
    
    
    
    }

    Take a guess which command doesn't like this method.  What's strange is that Powershell returns "The term 'Validate-Media -media MEDIA002' is not recognized... when it's clearly stated above.  I can even import the script as a module and call the function, it just doesn't like this method.  I have thought about possibly stating that it's a string, but I'm not sure here.  Other methods of structuring a tool and ordering functions would be appreciated as well.  Thanks everyone :)

    Ryan

    Thursday, November 20, 2014 8:28 PM

Answers

  • That's because PowerShell thinks the string 'Validate-Media -media MEDIA002' is the name of a command.

    When you use the & operator, the string immediately after & must be the command's name only (no parameters). Parameters must be appended afterwards separately.

    This article may help clear up some of the confusion:

    Windows IT Pro: Running Executables in PowerShell


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by MrBrooks Friday, November 21, 2014 2:33 PM
    Thursday, November 20, 2014 9:47 PM
    Moderator

All replies

  • That's because PowerShell thinks the string 'Validate-Media -media MEDIA002' is the name of a command.

    When you use the & operator, the string immediately after & must be the command's name only (no parameters). Parameters must be appended afterwards separately.

    This article may help clear up some of the confusion:

    Windows IT Pro: Running Executables in PowerShell


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by MrBrooks Friday, November 21, 2014 2:33 PM
    Thursday, November 20, 2014 9:47 PM
    Moderator
  • That makes sense.  I thought the method I was using would work because I was seeing the parameter translated correctly.  I suppose I can just grab that parameter from the tool script level instead.  Thanks Bill.
    Friday, November 21, 2014 2:34 PM
  • There is another way to approach this that can be useful.

    $commands=@(
    	{Test-Connection $pc}, 
    	{Validate-Media -media $media}, 
    	{Create-MDTUSB}, {Copy-Refresh},
    	{Copy-Wipe},
    	{Copy-Diskpart},
    	{Create-MDTMedia}
    )
    
    $pc=$env:COMPUTERNAME
    $commands | ForEach-Object{ $_.Invoke() }
    
    


    ¯\_(ツ)_/¯

    Friday, November 21, 2014 8:13 PM