How to open image.png using ps1 script?

扶醉桌前 提交于 2020-02-02 11:08:49

问题


Setting the below $usbDriveLetter variable to automatically find the USB drive letter, and using that variable to open an image on the USB doesn't work. It literally prints "G:\image.png" in the cmd.

$usbDriveLetter = (gwmi win32_volume -f 'label=''USB_NAME_HERE''').Name;
"$usbDriveLetter" + "image.png"

But if I don't use a var and make "G:\" static in the PowerShell script, the image opens just fine.

G:\image.png

So what am I doing wrong here? How do we dynamically open images using ps1 scripts?


回答1:


When combining two strings, you get a string. If you quote the path ("G:\image.png") it will behave the same.

Use Invoke-Item to execute the path:

$usbDriveLetter = (gwmi win32_volume -f 'label=''USB_NAME_HERE''').Name
Invoke-Item -Path ("$usbDriveLetter" + "image.png")

You may also use the call-operator &:

$usbDriveLetter = (gwmi win32_volume -f 'label=''USB_NAME_HERE''').Name
& ("$usbDriveLetter" + "image.png")



回答2:


Frode F.'s helpful answer provides effective solutions.

As for when you need &, PowerShell's call operator:

In order to execute a command / open a document that is not specified as an unquoted, literal string, you need &.

That is, & is needed whenever you specify the command name (or path) / document filename (or path):

  • either: as a quoted string (e.g., "G:\image.png")

  • or: as the result of an expression (e.g., ("$usbDriveLetter" + "image.png"); ditto for $(...))

Note:

  • In the case of opening a document (rather than invoking an executable), you may use Invoke-Item instead of &.

  • If you're trying to open a folder path in File Explorer, only Invoke-Item works.


As for why you need &:

PowerShell has two fundamental parsing modes:

  • argument mode, which works like traditional shells

  • expression mode, which works like traditional programming languages.

Running Get-help about_Parsing provides an introduction to these modes.

In short, it is the first token that determines which mode is applied, and in order to execute / open something, it must be parsed in argument mode (in expression mode, the result is simply output); thus, the 1st token must be:

  • either: a literal, unquoted command/document name or path, as stated.
  • or: &, in which case the next argument - which may then be specified as a quoted string or expression - is interpreted as the command / document name or path to execute / open.


来源:https://stackoverflow.com/questions/48872867/how-to-open-image-png-using-ps1-script

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