PS常用命令之文件和目录操作

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

[TOC]

目录和文件打开
Test-Path

描述:可以验证目录或者文件是否存在以及系统变量是否存在; 基础实例:

#1.验证文件夹目录是否存在
PS > test-path -Path C:Windows
True

#2.验证文件是否存在
PS C:UsersWeiyiGeek> test-path .test.py
True
PS C:UsersWeiyiGeek> test-path .nono.py
False

#3.验证变量是否存在
test-path variable:PWD
True
Get-ChildItem

基础示例:

#1.列举当前文件与目录(ls / gci / dir)
Get-ChildItem


#2.过滤文件
> Get-ChildItem -Name 1.txt
# 1.txt

> Get-ChildItem -Filter *.txt
# Mode                LastWriteTime     Length Name   
# -a---        2019/11/18     20:58          4 1.txt  


#3.指定显示(隐藏的)文件或者路径
ls -D
ls -File -Hidden
ls -File -Hidden -ReadOnly
# Mode          LastWriteTime     Length Name 
# ----          -------------     ------ ----                                         
# -arhs         2018/12/4     18:44       1006 ntuser.pol


#4.显示指定属性的文件或者目录
ls -Attributes a
Get-Content

描述:打开文本文件它的别名有cat以及Type等;

基础实例:

#1.打开一个文本文件test.txt
Get-Content .test.txt
# Powershell Routing
# Powershell Routing

筛选和过滤

Select-Object

描述:显示特定的列字段的数据;

基础实例:

get-process | Select-Object Handle,Id,ProcessName 
# Handle    Id ProcessName
# ------    -- -----------
#            0 Idle
#            4 System
#            8 svchost
#           68 svchost
#          104 Registry
# 3232     264 TXPlatform

PS> Get-service | Select-Object -First 2 #显示第一个或者前几个条目
# Status   Name               DisplayName
# ------   ----               -----------
# Stopped  AarSvc_48f8d       AarSvc_48f8d
# Stopped  AJRouter           AllJoyn Router Service
PS> Get-process | sort -Descending cpu | select -First 5 #列出占用CPU最大的5个进程


PS> Dir | Select-Object * -exclude *A* -ExcludeProperty "*N*" #支持通配符过滤
Where-Object

描述:它的主要作用是可以自定义过滤条件,并过滤从管道传递来的对象数据。(一般在管道符之后)

关系操作符号:

WeiyiGeek.

基础示例:

#1.获得C:Windows目录下所有大小超过200 bytes的文件。(? / where)
> Get-ChildItem C:Windows | Where-Object -FilterScript {$_.Length -gt 200}
> ls . | Where-Object -FilterScript {$_.Extension -eq ".txt"}
##目录: C:UsersAdministrator
# Mode                LastWriteTime     Length Name                                         ----                -------------     ------ ----                                         -a---        2019/11/18     20:58          4 1.txt      


#2.别名使用与like相似过滤
> ls . | ? -FilterScript {$_.BaseName -like "无线网络连接-GEEK"}


#3.我要获得所有名为svchost的进程信息。
> Get-Process | Where-Object{$_.ProcessName -eq "svchost"}
# Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
# -------  ------    -----      -----     ------     --  -- -----------
#     354      33     8956      11296       0.14    276   0 svchost
Get-Process | Where-Object ProcessName -EQ "svchost"  #PowerShell 3.0版本后Where就有了更简单的写法我们不需要?和{};
# 608      28    21124      23296    95     4.80    292 svchost   

#4.甚至可以筛选之后继续筛选(在JAVA中我们叫链式编程)
Get-Process | Where-Object{$_.ProcessName -eq "svchost"} | Where-Object{$_.Id -gt 1000}


#5.补充过滤案例
PS D:> get-alias | Where-Object -FilterScript {$_.Name -like 'sa*'}
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           sajb -> Start-Job
Alias           sal -> Set-Alias
Alias           saps -> Start-Process
Alias           sasv -> Start-Service
Select-String

描述:可以按照字符串以及属性进行过滤显示通过管道符;

#过滤选择显示特定的字符串
PS > ipconfig | Select-String "IPv6"
本地链接 IPv6 地址. . . . . . . . : fe80::d97d:fe6c:10bf:4244%15
本地链接 IPv6 地址. . . . . . . . : fe80::34d5:4b52:1627:64dc%14
本地链接 IPv6 地址. . . . . . . . : fe80::50fc:1560:33a5:b73f%5

排序与分组

Sort-Object

描述:主要是根据传递过来的对象的属性作为条件来进行排序或者升序,或者降序,别名是sort;

实际案例:

#1.通过ls获取当前目录的所有文件信息,然后通过Sort -Descending对文件信息按照Name降序排列,最后将排序好的文件的Name和Mode格式化成Table输出。
PS C:PStest> ls | sort -Descending Name | Format-Table Name,Mode
# Name        Mode
# d.txt       -a---
# c.txt       -a---


#2.完成主要关键字降序,次要关键字升序的排序
Dir | Sort-Object @{expression="Length";Descending=$true},@{expression="Name";Ascending=$true}
Get-Unique

描述:可以从已排序的对象列表中删除重复对象 Get-Unique会逐个遍历对象,每次遍历时都会与前一个对象进行比较,如果和前一个对象相等就会抛弃当前对象,否则就保留,与Linux中uniq命令有一致之处。 必须进行排序后再进行去重;

基础示例:

PS > 1,2,3,1 | Get-Unique
1
2
3
1

PS > 1,2,3,1 | Sort-Object| Get-Unique
1
2
3

PS > Get-ChildItem | foreach{$_.Extension} | Sort-Object | Get-Unique | Write-Host -NoNewline  #不换行显示(值得需学习)
.CHM.chw.docx.gz.jpg.lnk.png.properties.py.sql.txt
Group-Object

描述:主要是对数据进行分组

#按照状态进行分组显示
PS C:UsersWeiyiGeek> Get-Service | Group-Object Status | Format-Table -AutoSize -Wrap
Count Name    Group
----- ----    -----
  170 Stopped {AarSvc_48f8d, AJRouter, ALG, AppIDSvc...}
  103 Running {AMD External Events Utility, AnyShare Service, Appinfo, AudioEndpointBuilder...}


#当前目录的文件以扩展名进行分组
PS> ls | Group-Object Extension
Count Name   Group
----- ----   -----
    5        {11, 2, Dell-Latitude-E6330-Mojave-Hackintosh-EFI, 课件...}
    1 .py    {123.py}
    1 .gz    {back.tar.gz}
    9 .lnk   {eclipse.exe.lnk, Microsoft Edge.lnk, Postman.lnk, Resilio Sync.lnk...}


#根据当前应用程序的发布者分组
Get-Process | Group-Object Company -NoElement

文件解压缩

Compress-Archive | Archive-Archive

描述:从PS 5.0x开始进行支持将zip文件进行解压或者打包;

$Get-help Compress-Archive
Compress-Archive [-Path] <string[]> [-DestinationPath] <string>  [<CommonParameters>]
Expand-Archive [-Path] <string> [[-DestinationPath] <string>]  [<CommonParameters>]

#参数说明:
-Path 指定源路径+目录或者压缩文件
-DestinationPath 指定目标路径+目录或者压缩文件

基础示例:

#建立一个新文件
New-Item -ItemType File test.txt -Force

#压缩
Compress-Archive -Path "./test.txt" -DestinationPath "./psCompress.zip"

#解压
Expand-Archive -Path "./psCompress.zip" -DestinationPath "./psExpandArchive/"

格式化和转换

Format-*

描述:可以进行格式化文字进行展示;

  • Format-Custom: 使用自定义视图来设置输出的格式。
  • Format-List: 将输出的格式设置为属性列表,其中每个属性均各占一行显示。
  • Format-Table: 将输出的格式设置为表。
  • Format-Wide: 将对象的格式设置为只能显示每个对象的一个属性的宽表。

基础语法:

#对于任何一个对象都可以使用Format-List * , 查看它所有的属性和方法。
Format-List
      [[-Property] <Object[]>]
      [-GroupBy <Object>]
      [-View <string>]
      [-ShowError][-DisplayError]
      [-Force]
      [-Expand <string>]
      [-InputObject <psobject>]
      [<CommonParameters>]


Format-Table
      [-AutoSize]
      [-RepeatHeader]
      [-HideTableHeaders]
      [-Wrap]
      [[-Property] <Object[]>]
      [-GroupBy <Object>]
      [-View <String>]
      [-ShowError]
      [-DisplayError]
      [-Force]
      [-Expand <String>]
      [-InputObject <PSObject>]
      [<CommonParameters>]


#在格式-定制小命令格式化为以交替的视图定义的命令的输出
Format-Custom
      [[-Property] <Object[]>]
      [-Depth <Int32>]
      [-GroupBy <Object>]
      [-View <String>]
      [-ShowError] #通过管道发送错误
      [-DisplayError]
      [-Force]
      [-Expand <String>]
      [-InputObject <PSObject>]
      [<CommonParameters>]


#显示一个文件或其他输入十六进制。
Format-Hex
      -InputObject <psobject>
      [-Encoding <Encoding>]
      [-Count <long>]
      [-Offset <long>]
      [-Raw]
      [<CommonParameters>]

基础实例:

#1.Format-List案例
PS > Get-process | Format-List
# Id      : 3108
# Handles : 196
# CPU     : 
# SI      : 0
# Name    : wsctrl
PS > Get-process | Format-List -Property Name
# Name    : wsctrl

PS > ls | Format-List * | Out-Host -Paging #查看对象它所有的属性和方法。
# PSPath            : Microsoft.PowerShell.CoreFileSystem::C:UsersWeiyiGeek.android
# PSParentPath      : Microsoft.PowerShell.CoreFileSystem::C:UsersWeiyiGeek
# PSChildName       : .android
# PSDrive           : C
# PSProvider        : Microsoft.PowerShell.CoreFileSystem
# PSIsContainer     : True
# Mode              : d-----
# BaseName          : .android
# Target            : {}
# LinkType          :
# Name              : .android
# FullName          : C:UsersWeiyiGeek.android
# Parent            : WeiyiGeek
# Exists            : True
# Root              : C:
# Extension         : .android
# CreationTime      : 2019/7/26 8:45:03
# CreationTimeUtc   : 2019/7/26 0:45:03
# LastAccessTime    : 2019/7/26 8:45:03
# LastAccessTimeUtc : 2019/7/26 0:45:03
# LastWriteTime     : 2019/7/26 8:45:03
# LastWriteTimeUtc  : 2019/7/26 0:45:03
# Attributes        : Directory
# <SPACE> 下一页;<CR> 下一行;Q 退出


#2.Format-Table案例
PS > ls | Format-Table *  #因为属性和属性的内容太多可能不会显示完全,可以使用文本换行参数
PS > ls | Format-Table * -Wrap  -AutoSize #换行显示并且通过-auto参数对列的宽带进行优化,会将属性值的最大宽带作为每一列的宽度
PS > ls | Format-Table Name,{ [int]($_.Length/1kb) } -Wrap  #脚本块作为属性
PS > ls | Format-Table Name,@{ Expression={[int]($_.Length/1kb)};Label="Kb"} -Wrap  #可以使用Lable设置显示列头为KB而不是[int]($_.Length/1kb)
# Name                 KB
# ----                ----------------------
# .gitconfig                               0
# .viminfo                                 8
# .vimrc                                  11


PS > Get-process | Format-Table -Property Handle,Name -AutoSize
# Handle Name                                                 
# ------ ----    
# 5544   ApplicationFrameHost   

PS > $column1 = @{expression="Name"; width=30;label="filename"; alignment="left"}
PS > $column2 = @{expression="LastWriteTime"; width=40;label="last modification"; alignment="right"}  
PS > ls | Format-Table $column1, $column2
# filename          last modification
# --------          -----------------
# .android          2019/7/26 8:45:03
# .config           2019/8/19 17:27:45

ls | Sort-Object Extension, Name | Format-Table -groupBy Extension  #GroupBy的参数完成分组


#4.默认输入与Format-Custom比较案例
Get-Process Winlogon
# Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
# -------  ------    -----      -----     ------     --  -- -----------
#     272      12     2900      12024               932   1 winlogon
PS D:> Get-Process Winlogon | Format-Custom
class Process
# {
#   Id = 932
#   Handles = 272
#   CPU =
#   SI = 1
#   Name = winlogon
# }


#5.Format-Hex 将文字或者文件转换成为十六进制数据
PS> 'WeiyiGeek' | Format-Hex
#00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
#00000000   57 65 69 79 69 47 65 65 6B     WeiyiGeek  

PS> Format-Hex -Path .File.t7f
# Path: C:TestFile.t7f
# 00000000   25 50 44 46 2D 31 2E 35 0D 0A 25 B5 B5 B5 B5 0D  %PDF-1.5..%????.

导入导出特定文件

ConvertTo-Html

描述:创建显示一个或一组对象的 HTML 页。

ConvertTo-Html [[-property] <Object[]>] [-inputObject <psobject>] [-body <string[]>] [-head <string[]>] [-title <string>] [<CommonParameters>]

基础实例:

#1.编写一些基本的控制语句来判断Handles数值的大小,到了一定数值后就用特定的颜色来以此标明
Get-Process | Select-Object Handles,ProcessName| Sort-Object Handles | Where-Object -FilterScript {$_.Handles -ge 300} |  ConvertTo-Html -Title "This is a Process Table" -Body "<H3>This is a Process Table</H3>" |
ForEach {$_ -replace "<tr>","<tr bgcolor=cyan>"} |
Foreach {
  if ($_ -like "*<td>5??</td>*") {
    $_ -replace "<tr bgcolor=cyan>","<tr bgcolor=red>"
  } elseif ($_ -like "*<td>6??</td>*") {
    $_ -replace "<tr bgcolor=cyan>","<tr bgcolor=green>"
  } else {$_}
  }  > D:/ps.htm

WeiyiGeek.

PS > Get-Host | ConvertTo-Html -Title "Cureent Host Info" -Body "<H3>Test ConvetTO-Html</H3>" | ForEach {$_ -replace "<tr>","<tr bgcolor=cyan>"}  > D:ps.htm #方式1
PS > Get-Service | ConvertTo-Html -Title "ls result" | Out-File a.html  #方式2
PS > start D:ps.htm

WeiyiGeek.

XML
  • Import-Clixml

Import-Clixml .before.xml #反序列化 .xml
  • Export-*
Get-Process | Export-Clixml before.xml #导出进程信息到xml中
CSV

描述:

Get-Service | Export-Csv a.csv ; . a.csv