Executing a command stored in a variable from PowerShell

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Executing a command stored in a variable from PowerShell

Message par ForumBot »

Executing a command stored in a variable from PowerShell
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Executing a command stored in a variable from PowerShell

Message par ForumBot »

Here is yet another way without `Invoke-Expression` but with two variables
(command:string and parameters:array). It works fine for me. Assume
`7z.exe` is in the system path.

`$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

```

If the command is known (7z.exe) and only parameters are variable then this will do

`$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

```

BTW, `Invoke-Expression` with one parameter works for me, too, e.g. this works

`$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

```

P.S. I usually prefer the way with a parameter array because it is easier to
compose programmatically than to build an expression for `Invoke-Expression`.
Répondre

Revenir à « PowerShell »