Invoke-Expression with exe in Program Files

戏子无情 提交于 2019-12-04 17:54:57

问题


I'm trying to run a Powershell command to call 7-Zip to zip up a folder using the following command:

$command = $SevenZip + " a " + $targetDirForZip + $GetDateName + "_" + $dir.Name + ".7z " + $dir.FullName
Invoke-Expression $command

The variables being fed into $command are already set and $SevenZip is "c:\Program Files\7-Zip\7z.exe"

This isn't working and I'm trying to work out the best way to call 7-Zip from Powershell. Ideas?


回答1:


I've had the same problem before. This is code (almost) straight from a backup script that I use currently:

[string]$pathToZipExe = "C:\Program Files\7-zip\7z.exe";
[Array]$arguments = "a", "-tgzip", $outputFilePath, $inputFilePath;

& $pathToZipExe $arguments;

I've gotten into the habit of using an argument array with the call operator, It seems to be more robust than other methods.




回答2:


You don't need to use Invoke-Expression just use the invocation (call) operator & to invoke a string that names a command to execute. Note that you want to keep the parameters separate in this case i.e. the string SevenZip should just be the path to the EXE e.g.:

&$SevenZip a "$targetDirForZip$GetDateName_$($dir.Name).7z" $dir.FullName



回答3:


You actually don't need Invoke-Expression. You can simply invoke the command by using the ampersand such as:

&$Command

But there's also the Start-Process cmdlet which might be better suited for what you're trying to do. By executing the command as a string above, you're prone to errors if the $SevenZip contains spaces and is not quoted. Instead I would use:

Start-Process $SevenZip "...rest..."



回答4:


I ran into this problem as well, here was my solution.

invoke-expression "& 'C:\Program Files\CIESetupClient\Staging\ffd4bc34-52c1-43e7-92d4-93d2f59d7f52\vstor_redist.exe' /q /norestart /log c:\Logs\VSTOR_Redist.log "

i was able to leave my paramaters outside the single quotes pointing to my exe, i think this is probably the easiest way to call an exe with parameters using invoke-expression.




回答5:


Let me guess, it's trying to invoke "c:\Program"?

Not sure of the correct syntax for PS, but you'll need to do something about that space.




回答6:


Works for me:

$command = "& ""$SevenZip""" + " a " + $targetDirForZip + $GetDateName + "_" + $dir.Name + ".7z " + $dir.FullName

Write-Host "Running: $command"

Invoke-Expression $command



回答7:


You can also use MS-DOS commands from within a Windows PowerShell script.

I've always loved CMD.exe's START command, which allows you to start an command in parallel.

So to start your 7-zip, put the following command in your Powershell script:

    cmd.exe /c start <your 7-zip command like in MS-DOS> 


来源:https://stackoverflow.com/questions/1917507/invoke-expression-with-exe-in-program-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!