从 PowerShell 执行存储在变量中的命令 [英] Executing a command stored in a variable from PowerShell

查看:57
本文介绍了从 PowerShell 执行存储在变量中的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命令,我已经在 PowerShell 中构建并存储在一个变量中.如果我执行 Write-Host 并复制并粘贴到标准 cmd.exe 窗口.

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?

我尝试了几种 Invoke-Command 或 Invoke-Expression 的组合,但都没有成功.

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_logs\site-host-at-web1-100827.zip c:\inetpub\logs\logfiles\w3svc1\u_ex100827.log

推荐答案

这是另一种没有 Invoke-Expression 但有两个变量的方法(命令:字符串和参数:数组).这对我来说可以.认为7z.exe 在系统路径中.

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

如果命令是已知的 (7z.exe) 并且只有参数是可变的,那么就可以了

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

顺便说一句,带有一个参数的 Invoke-Expression 也适用于我,例如这有效

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

附言我通常更喜欢使用参数数组的方式,因为它更容易以编程方式组合而不是为 Invoke-Expression 构建表达式.

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.

这篇关于从 PowerShell 执行存储在变量中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆