Windows Powershell 执行外部命令

2019-09-30 15:13:13刘景俊

启动外部程序

为什么可以通过notpad打开记事本,不能通过wordpad打开写字板?
因为notepad.exe位于C:Windowssystem32 这个目录,而这个目录已经默认被包含在Powershell的环境变量$env:Path中。

C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:Program Files (x
86)Windows Kits8.1Windows Performance Toolkit;C:Program FilesMicrosoft SQL Server110ToolsBinn;C:Program File
s (x86)Microsoft SDKsTypeScript1.0;C:Program FilesMicrosoftWeb Platform Installer

而wordpad.exe 所在的“%ProgramFiles%Windows NTAccessorieswordpad.exe“目录却没有包含,可以先进入这个目录,再运行wordpad,或者将wordpad所在的目录加入到环境变量中,$env:Path=$env:Path+”%ProgramFiles%Windows NTAccessories”。

默认键入一个字符串,powershell会将它原样输出,如果该字符串是一个命令或者启动程序,在字符串前加‘&'可以执行命令,或者启动程序。

PS C:PS> "ls"
ls
PS C:PS> &"ls"

  Directory: C:PS

Mode        LastWriteTime   Length Name
----        -------------   ------ ----
d----    2011/11/23   17:25      ABC
-a---    2011/11/23   17:36     14 a.txt
-a---    2011/11/23   17:25     0 b.txt
-a---    2011/11/23   17:25     0 c.txt
-a---    2011/11/23   17:25     0 d.txt
-a---    2011/11/23   17:37    242 test.txt

PS C:PS> "cmd.exe"
cmd.exe
PS C:PS> &"cmd.exe"
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.