Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

Executing a command stored in a variable from PowerShell

I have a command that I have build and stored in a variable in PowerShell. This command works if I do a Write-Host and copy and paste into a standard cmd.exe window.

How do I execute this command from inside my script?

I have tried several combination of Invoke-Command or Invoke-Expression with no luck.

This is how I built the variable:

$cmd1 = $arcprg + $arcdir + "" + $site1 + "-" + $hst + "-" + $yesterday + ".zip " + $logpath1 + "u_ex" + $yesterday + ".log"

This is what the variable looks like if it is printed to the screen:

7z.exe a -tzip c:arc_logssite-host-at-web1-100827.zip c:inetpublogslogfilesw3svc1u_ex100827.log
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:empwith spaceest1.zip', 'C:TEMPwith spacechangelog'

& $cmd $prm

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

$prm = 'a', '-tzip', 'c:empwith spaceest1.zip', 'C:TEMPwith spacechangelog'

& 7z.exe $prm

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

$cmd = '& 7z.exe a -tzip "c:empwith spaceest2.zip" "C:TEMPwith spacechangelog"'

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...