Powershell命令与实例初识2

时间:2022-07-28
本文章向大家介绍Powershell命令与实例初识2,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

[TOC]

前言

人生莫大的痛苦,莫过于学习下面这些命令参数,但是为了更好的掌握它又不得不去了解;

PS脚本语言语Linux上的Shell有一致之处,这也是我为什么脱离了Bat而进入PS坑的原因;

进程与服务

-Process

进程常用cmdlet命令:

#1.获取进程相关的cmdlet命令
PS > (Get-Command *-Process).Name  #值得学习
Debug-Process
Get-Process
Start-Process
Stop-Process
Wait-Process

基础示例:

#1.获取进程进行 (gps / ps)
get-Process
get-Process -Name notepad  #获取指定运行经常的消息
# Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                   
# -------  ------    -----      ----- -----   ------     -- -----------                   
#     467      37    20916      50980   248     2.01   5600 notepad   


#2.启动进程( saps / start)
Start-Process C:WindowsSystem32notepad.exe 1.txt -WindowStyle Maximized  # hidden
 

#3.使进程等待 (关闭)
Wait-Process -Id 5600
Wait-Process -Name notepad -Timeout 10

#4.停止进程 ( spps / kill)
Stop-Process -ID 7960
Stop-Process -Name notepad -Force  #强制结束
-Services

服务常用的cmdlet命令:

> (Get-Command *-Service).Name
Get-Service
New-Service
Restart-Service
Resume-Service  #恢复挂起服务
Set-Service
Start-Service
Stop-Service
Suspend-Service #延缓挂起服务

基础信息:

#1.服务信息获取
Get-Service -Name RpcSs
# Status   Name               DisplayName                      
# ------   ----               -----------        
# Running  RpcSs              Remote Procedure Call (RPC)  

Get-Service RpcSs -RequiredServices   #查看其被依赖的的服务  
# Running  DcomLaunch         DCOM Server Process Launcher     
# Running  RpcEptMapper       RPC Endpoint Mapper  


#2.启动服务
Start-Service RpcSs
Start-Service -Name RpcSs


#3.暂停服务
Stop-Service  RpcSs -Force

网络连接

Test-Connection

描述:可以类比于cmd中的nbtstat进行获取局域网中的指定计算机名的IPv4/6地址信息以及MAC地址;

#1.获取本机计算机名相关信息
PS C:UsersWeiyiGeek> Test-Connection -ComputerName WeiyiGeek
Source        Destination     IPV4Address      IPV6Address                 Bytes    Time(ms)
------        -----------     -----------      -----------                 -----    --------
WEIYIGEEK     WeiyiGeek       10.10.10.10    fe80:::fe6c:10bf:4244%15         32       0

变量操作

描述:为了管理变量PS提供了五个专门管理变量的命令

  • Get-Variable
  • Set-Variable
  • New-Variable
  • Remove-Variable
  • Clear-Variable
GetType

描述:获取变量的类型

PS C:UsersWeiyiGeek> Get-Help gettype*
PS C:UsersWeiyiGeek> $var=1024;$var.gettype()
IsPublic IsSerial Name     BaseType
-------- -------- ----     --------
True     True     Int32    System.ValueType
New-Variable

描述:以在定义变量时指定变量的一些其它属性,比如访问权限描述;

变量的选项是一个枚举值包含:

  • “None”:默认设置
  • “ReadOnly”:变量只读,但是可以通过-Force 选项更新。
  • “Constant”:常量一旦声明,在当前控制台不能更新。
  • “Private”:只在当前作用域可见,不能贯穿到其它作用域
  • “AllScope”:全局,可以贯穿于任何作用域

基础实例:

#1.使用New-Variable命令实例
PS C:test> New-Variable num -Value 100 -Force -Option readonly  #option选项 在创建变量时给变量加上只读属性
PS C:test> new-variable num -Value "strong" -Option constant    #常量一旦声明不可修改,权限更高的变量选项Constant,
PS C:test> $num=101
# Cannot overwrite variable num because it is read-only or constant.

#2.变量描述可以通过-description 添加变量描述,但是变量描述默认不会显示,可以通过Format-List 查看。
PS C:test> new-variable name -Value "me" -Description "This is my name"
PS C:test> ls Variable:name | fl *
# PSPath        : Microsoft.PowerShell.CoreVariable::name
# PSDrive       : Variable
# PSProvider    : Microsoft.PowerShell.CoreVariable
# PSIsContainer : False
# Name          : name
# Description   : This is my name
Set-Variable

描述:设置变量

#1.设置变量为只读属性并且进行描述强制执行
$var="SetVariable"
Set-Variable var -Option "ReadOnly" -Description "This is readOnly"  -Force
Get-Variable

描述:利用该命令获取创建的变量相关的信息;

#0.常规查看变量
PS C:test> Get-Variable home
# Name    Value
# ----    -----
# HOME    C:UsersWeiyiGeek


#1.可以使用PS子表达式直接更改对象属性内容
PS C:test> (Get-Variable str).Description="变量的描述已更改;"

时间日期

Get-Date

描述:时间日期对象可以直接利用其属性计算出当前年中的天数以及几天前和一天后的日期等等;

Get-Date | Format-Custom {$_} #$_表示管道中当前对象
class DateTime
{
  $_ = class DateTime
    {
      Day = 27
      DayOfWeek = Wednesday
      DayOfYear = 331
      Hour = 15
      Kind = Local
      Millisecond = 132
      Minute = 41
      Month = 11
      Second = 5
      Ticks = 637104660651327983
      TimeOfDay = 
        class TimeSpan
        {
          Ticks = 564651327983
          Days = 0
          Hours = 15
          Milliseconds = 132
          Minutes = 41
          Seconds = 5
          TotalDays = 0.653531629609954
          TotalHours = 15.6847591106389
          TotalMilliseconds = 56465132.7983
          TotalMinutes = 941.085546638333
          TotalSeconds = 56465.1327983
        }
      Year = 2019
      DateTime = 2019年11月27日 15:41:05
    }
}
#系统当前时间
PS C:UsersWeiyiGeek> date
2019年11月27日 15:08:07
PS C:UsersWeiyiGeek> [DateTime]::Now
2019年11月27日 15:07:54
[DateTime]类
#时间加减
PS D:> [DateTime]"2019-11-28 15:16:20" - ([DateTime]::Now)
Days              : 0
Hours             : 23
Minutes           : 59
Seconds           : 37
Milliseconds      : 373
Ticks             : 863773731705
TotalDays         : 0.999738115399305
TotalHours        : 23.9937147695833
TotalMinutes      : 1439.622886175
TotalSeconds      : 86377.3731705
TotalMilliseconds : 86377373.1705


#时间累加
([DateTime]::Now).AddHours(1)
2019年11月27日 16:15:33

#将一个字符串转换成DateTime类
[System.DateTime]::Parse("2012-10-13 23:42:55")


#打印1988到2000年的所有闰年
for($year=1988;$year -le 2000;$year++)
{
    if( [System.DateTime]::IsLeapYear($year) ){
      Write-Output $year
    }
}
[Math] 类

描述:这是一个数学类里面定义很多实用的静态方法;

#例如.求绝对值,三角函数,取整
PS > [Math]::Abs(-10.89)
10.89
PS > [Math]::Sin([Math]::PI/2)
1
PS > [Math]::Truncate(2012.7765)
2012
[NET] 类

描述:.NET支持成千上万的类型,有了这些类型可以做许多事情,幸运的是Powershell恰好支持这些类型。

#1.例如使用System.Net.IPAddress类将字符串IP地址转换成一个IPAddress实例
PS C:UsersWeiyiGeekDesktop>  [Net.IPAddress]'10.3.129.71'
Address            : 1199637258
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 10.3.129.71


#2.根据IP地址查看主机名,8.8.8.8是谷歌的免费DNS服务器
PS > [system.Net.Dns]::GetHostByAddress('8.8.8.8') | fl
HostName    : google-public-dns-a.google.com
Aliases     : {}
AddressList : {8.8.8.8}
[AppDomain] 类

.NET中的类型定义在不同的程序集中,首先得知道当前程序已经加载了那些程序集; AppDomain类可以完成这个需求,因为它有一个静态成员CurrentDomain,CurrentDomain中有一个GetAssemblies()方法。

PS > [AppDomain]::CurrentDomain

PS > [AppDomain]::CurrentDomain.GetAssemblies()
GAC    Version        Location
---    -------        --------
True   v4.0.30319     C:WindowsMicrosoft.NETFramework64v4.0.30319mscorlib.dll

PS > [AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object { $_.GetExportedTypes() } | Where-Object { $_ -like $searchtext } | ForEach-Object { $_.FullName }
[Environment] 类
PS > [Environment]::UserDomainName #当前登录域
MyHome
PS > [Environment]::UserName #当前用户名
xiaoming
PS > [Environment]::MachineName #当前机器名
LocalHost