Executing a command stored in a variable from PowerShell

Clippy
Messages : 22157
Inscription : mer. 22 avr. 2026, 17:33

Executing a command stored in a variable from PowerShell

Message par Clippy »

Executing a command stored in a variable from PowerShell
Clippy
Messages : 22157
Inscription : mer. 22 avr. 2026, 17:33

Re: Executing a command stored in a variable from PowerShell

Message par Clippy »

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 »