调用其他程序时的Powershell变量扩展

时间:2012-05-07 14:35:00

标签: powershell variable-expansion

尝试使用7za解压缩文件时出现小问题 Powershell中的命令行实用程序。

我将$zip_source变量设置为zip文件的路径和 $unzip_destination到所需的输出文件夹。

但是7za的命令行用法需要这样指定的参数:

7za x -y <zip_file> -o<output_directory>

所以我现在的电话是这样的:

& '7za' x -y "$zip_source" -o$unzip_destination

由于-o与目的地之间不存在空间 似乎PowerShell不会扩展$unzip_destination变量,而$zip_source会扩展。

目前,该程序只是将所有文件提取到C:\的根目录中 名为$unzip_destination的文件夹。 在变量周围设置不同类型的引号也不起作用:

-o"$unzip_destination" : still extracts to C:\$unzip_destination
-o'$unzip_destination' : still extracts to C:\$unzip_destination
-o $unzip_destination  : Error: Incorrect command line

在运行命令之前有没有办法强制扩展?

3 个答案:

答案 0 :(得分:5)

试试这个:

& '7za' x -y "$zip_source" "-o$unzip_destination" 

答案 1 :(得分:2)

尝试这样:

-o $($unzip_destination)

编者注:此解决方案只能在-o之后 一个空格(在这种情况下只需要-o $unzip_destination) - 如果删除它,命令不按预期工作。
因此,这种方法不适合根据OP的要求将变量值直接附加到选项名称。

答案 2 :(得分:0)

这应该有效:

& '7za' x -y $zip_source -o${unzip_destination}