111 发表于 2018-9-3 07:07:45

Powershell之 运行方式篇

  Powershell有很多种不同的运行方式,每一种运行方法都有自个的用途,主要包括以下几种方法:
  1.直接运行
  2.Invoke-Expression
  3.Invoke-Command
  4.Invoke-Item
  5.操作符&
  6.cmd /c
  7.Start-Process
  8.::start()
  9.WMI win32_Process Create()
  一.直接运行——使用环境路径或者本地路径
  用途:简单、使用
  实例:
  #运行指令ping,无需前缀".\", 因为它在system32文件夹(这是环境路径)
  ping localhost
  #test.ps1存在当前路径,运行test.ps1,需带前缀".\"
  .\test.ps1
  
  二.Invoke-Expression
  用途:主要针对字符串的执行
  实例:
  $str = "Get-Host";
  Invoke-Expression $str;
  
  三.Invoke-Command
  用途:通过WSMAN方式 在多台电脑上执行代码
  $scriptblock={gwmi win32_ComputerSystem};
  Invoke-Command -scriptblock $scriptBlock -computerName "computer1","computer2"
  
  四.Invoke-Item
  用途:强制用默认方式来操作项,可同时打开多个
  实例:
Invoke-Item*.xls  五.操作符&
  用途:将字符串当做单行命令符来操作,主要用于带有空格的命令
  实例:
  & 'c:\Program Files\test.ps1'
  
  六. cmd /c
  用途: 绕过Powershell,用cmd shell来运行指令。在powershell v2.0中效率比直接运行更高,但在
  powershell v3.0几乎很少使用
  实例:
cmd /c dir c:\  
  七.Start-Process
  用途:启动进程执行程序,并返回.Net进程对象
  实例:
  $p = Start-Process ping -Argument 127.0.0.1
  $p.HasExited
  
  八. start()
  用途:比Start-Process有更多的可控参数选择
  实例:
  $p = New-Object System.Diagnostics.Process
  $p.StartInfo.FileName = "ipconfig";
  $p.StartInfo.Arguments = " /all";
  $p.StartInfo.RedirectStandardOutout = $True;
  $p.StartInfo.UseShellExecute = $false;
  $p.Start();
  $p.WaitForExit();
  九.Win32_Process Create()
  用途:通过RPC 可运行于本地或远程,而非WSMAN(Invoke-Command),返回ManagementBaseObject对象
  实例:
Invoke-WMIMethod -class Win32_Process -name Create -computerName "computer1" -ArgumentList notepad.exe("Win32_Process").create('notepad.exe')
页: [1]
查看完整版本: Powershell之 运行方式篇