zl程序教程

您现在的位置是:首页 >  其它

当前栏目

PS常用命令之文件目录及内容操作

操作 内容 常用命令 PS 文件目录
2023-06-13 09:13:35 时间

[TOC]

0x01 目录和文件操作

Test-Path 命令 - 验证目标文件目录是否存在

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

语法参数:

Test-Path [-Path] <string[]>  [<CommonParameters>]
Test-Path  [<CommonParameters>]

基础实例:

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

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

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

#4.判断注册表项是否存在(HKCU:, HKLM预定义的两个重要注册表根目录虚拟驱动器)
Test-Path "HKCU:HKEY_CURRENT_USER\Remote"  # True
Test-Path "HKCU:HKEY_CURRENT_USER\Remote1" # False
Test-Path "Registry::HKEY_CURRENT_USER\Remote"     # True

Set-Location 命令 - 将当前工作位置设置为指定位置。

描述: 切换当前工作目录的路径实际上在PowerShell中cd命令就是其的别名。

基础语法:

Set-Location [[-Path] <System.String>] [-StackName <System.String>] -LiteralPath <System.String> [-PassThru] [-UseTransaction] [<CommonParameters>]

基础示例:

# Example 1.此命令将当前位置设置为`HKLM:`驱动器的根目录(访问注册表)。
PS C:\> Set-Location -Path "HKLM:\"
PS C:\> Set-Location -Path "HKCU:\"
PS HKCU:\> ls
  # Hive: HKEY_CURRENT_USER
  # Name                           Property
  # ----                           --------
  # AppEvents
  # CLSID
  # Console                        ColorTable00             : 789516
# 例如: 更改当前(键)目录
PS C:\> cd "Registry::HKEY_CURRENT_USER\Remote"
PS Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Remote>

#Example 2.设置当前位置并显示该位置
PS C:\> Set-Location -Path "Env:\" -PassThru
  # Path
  # ----
  # Env:\
PS Env:\> $Env:ComSpec
C:\WINDOWS\system32\cmd.exe
PS Env:\> start-process $Env:ComSpec


#Example 3.将location设置为C:驱动器中的当前位置
PS C:\Windows\> Set-Location HKLM:\
PS HKLM:\> Set-Location C:
PS C:\Windows\> Get-Location
  # C:\Windows

#Example 4: 将当前位置设置为命名堆栈 (路径别名)
# 第一个命令将当前位置添加到路径堆栈。
PS C:\> Push-Location -Path 'C:\Program Files\PowerShell\' -StackName "Paths" 
# 第二个命令使路径位置堆栈成为当前位置堆栈。
PS C:\Program Files\PowerShell\> Set-Location -StackName "Paths"
# 第三个命令显示当前位置堆栈中的位置。
PS C:\Program Files\PowerShell\> Get-Location -Stack
Path
----
C:\

Get-Item 命令 - 在特定位置获取项目

描述: 在特定位置获取项目,除非使用*通配符来请求项目的所有内容,否则此cmdlet不会在指定位置获取项目的内容。

Tips : PowerShell提供程序使用此命令来浏览不同类型的数据存储。

语法参数:

Get-Item
  [-Path] <String[]>
  [-Filter <String>]
  [-Include <String[]>]
  [-Exclude <String[]>]
  [-Force]
  [-Credential <PSCredential>]
  [-Stream <String[]>]
  [<CommonParameters>]

# 重要参数
-LiteralPath #参数指定一个或多个位置的路径。它的值与键入时完全一样。不解释通配符。如果路径包含任何转义字符,则将其用引号引起来。 单引号告诉Windows PowerShell不要将任何字符解释为转义序列。
-Stream     #参数用于从文件中获取特定的备用NTFS文件流,支持通配符。 使用星号*来获取所有流。 -Stream参数在文件夹上无效。它是一个动态参数,仅在文件系统驱动器中起作用。

使用实例:

# 示例1: 获取当前位置以及指定盘符
PS C:\Users\WeiyiGeek> Get-Item C:\
PS C:\Users\WeiyiGeek> get-item .
  # 目录: C:\Users
  # Mode                 LastWriteTime         Length Name
  # ----                 -------------         ------ ----
  # d-----         2021/2/19     18:05                WeiyiGeek


# 例2:获取当前目录下的所有条目
PS C:\Users\WeiyiGeek> Get-Item *
  Directory: C:\ps-test
  Mode                LastWriteTime     Length Name
  ----                -------------     ------ ----
  d----         7/26/2006   9:29 AM            Logs
  d----         7/26/2006   9:26 AM            Recs
PS C:\Users\WeiyiGeek> Get-Item C:\*


# 例3:获取指定目录下的属性
(Get-Item "F:\2019\answer\*").name # 文件名称 12656.pdf
(Get-Item "F:\2019\answer\*").FullName # F:\2019\answer\12656.pdf
(Get-Item C:\Windows\System32\calc.exe).LastAccessTime
  # 2021年3月9日 9:28:51
(Get-Item C:\Windows\System32\calc.exe).Mode
  # -a----
(Get-Item C:\Windows\System32\calc.exe).Directory  # 父目录
  # Mode                 LastWriteTime         Length Name
  # ----                 -------------         ------ ----
  # d-----         2021/3/21     14:53                System32

# 例4:显示注册表项的内容
Get-Item 'HKLM:\Software\Microsoft\Powershell\1\Shellids\Microsoft.Powershell\'
  # Hive: HKEY_LOCAL_MACHINE\Software\Microsoft\Powershell\1\Shellids
  # Name                           Property
  # ----                           --------
  # Microsoft.Powershell           Path : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

# 远程桌面开放端口相关信息
(Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp\').Name
  # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp
(Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp\' |  Select-Object Property).Property
  # InteractiveDelay   # 键名
  # ....
  # PortNumber
  # RequiredPds
  # ServiceName
Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\' | % {$_.GetValue("PortNumber")}  # 采用循环取单个值得学习
Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp\' | % {$_.GetValue("PortNumber")}  # 3389
(Get-Item -Path "Registry::HKEY_CURRENT_USER\Remote").name        # HKEY_CURRENT_USER\Remote
(Get-Item -Path "Registry::HKEY_CURRENT_USER\Remote").SubKeyCount # 1


# 例5:获取具有排除项的目录中的项
Get-Item C:\Windows\*.* -Exclude "w*"

# 例6:获取硬链接信息
# 在PowerShell 6.2中,添加了另一个视图来获取硬链接信息。要获得硬链接信息,
Get-Item -Path C:\PathWhichIsAHardLink | Format-Table -View childrenWithHardlink

# 例7:非windows操作系统的输出
# In PowerShell 7.1 on Unix systems, the Get-Item cmdlet provides Unix-like output:
PS> Get-Item /Users
  # Directory: /
  # UnixMode    User  Group   LastWriteTime      Size  Name
  # --------    ----  -----   -------------      ----  ----
  # drwxr-xr-x  root  admin   12/20/2019 11:46   192   Users
#The new properties that are now part of the output are:
  # UnixMode is the file permissions as represented on a Unix system
  # User is the file owner
  # Group is the group owner
  # Size is the size of the file or directory as represented on a Unix system

# 例8.为Stream参数指定通配符以显示最近创建的文件的所有流。
  # PSPath        : Microsoft.PowerShell.Core\FileSystem::C:\Users\WeiyiGeek\LineNumbers.txt::$DATA
  # PSParentPath  : Microsoft.PowerShell.Core\FileSystem::C:\Users\WeiyiGeek
  # PSChildName   : LineNumbers.txt::$DATA
  # PSDrive       : C
  # PSProvider    : Microsoft.PowerShell.Core\FileSystem
  # PSIsContainer : False
  # FileName      : C:\Users\WeiyiGeek\LineNumbers.txt
  # Stream        : :$DATA
  # Length        : 1792

# 补充示例:
# 1) 获取当前目录下文件和目录的总数(默认一级目录)对象自带
(Get-Item *).count
20

Get-ChildItem 命令 - 获取一个或多个指定位置中的项和子项

描述: 获取指定目录中文件获取一个或多个指定位置中的项和子项,并且支持通配符过滤, Dir与ls是其别名。

语法参数:

# Alias  ls -> Get-ChildItem

# 语法
Get-ChildItem [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device | Directory | Encrypted | Hidden | IntegrityStream | Normal | NoScrubData | NotContentIndexed | Offline | ReadOnly | ReparsePoint | SparseFile | System | Temporary}] [-Depth <System.UInt32>]
[-Directory] [-Exclude <System.String[]>] [-File] [-Force] [-Hidden] [-Include <System.String[]>] -LiteralPath <System.String[]> [-Name] [-ReadOnly] [-Recurse] [-System] [-UseTransaction] [<CommonParameters>]

Get-ChildItem [[-Path] <System.String[]>] [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device | Directory | Encrypted | Hidden | IntegrityStream | Normal | NoScrubData | NotContentIndexed | Offline | ReadOnly | ReparsePoint | SparseFile | System | Temporary
}] [-Depth <System.UInt32>] [-Directory] [-Exclude <System.String[]>] [-File] [-Force] [-Hidden] [-Include <System.String[]>] [-Name] [-ReadOnly] [-Recurse] [-System] [-UseTransaction] [<CommonParameters>]

# 文件属性: 
------ | [dl]arhs-
l : 连接文件
d : 目录
a : 文本文件
r : 只读文件
h : 隐藏文件
s : 系统文件

基础示例:

# 1.列举当前文件与目录(ls / gci / dir)
Get-ChildItem
  # 目录: C:\Users\WeiyiGeek\Links
  # Mode                 LastWriteTime         Length Name
  # -a----         2020/11/5      9:06            541 Desktop.lnk
  # -a----         2020/11/5      9:06            970 Downloads.lnk
  # -a----         2020/5/15     11:30            858 Nextcloud.lnk

# 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  
Get-ChildItem -Path C:\Test\ -Include *.txt     # 包含通配符匹配到的文件
Get-ChildItem -Path C:\Test\Logs\* -Exclude A*  # 排除通配符匹配到的文件或者目录
Get-ChildItem -Path C:\Parent -Depth 2 # 使用Depth参数获取项(深度)


# 3.获取当前目录和子目录中的子项(递归显示)
Get-ChildItem -Path C:\Test\*.txt -Recurse -Force


# 4.指定内置属性例如显示(隐藏的)文件或者路径进行过滤
ls -D
ls -File -Hidden
ls -File -Hidden -ReadOnly
  # Mode          LastWriteTime     Length Name 
  # -arhs         2018/12/4     18:44       1006 ntuser.pol
# 可选参数: ReadOnly, Hidden, System, Directory, Archive, Device, Normal, Temporary, SparseFile, ReparsePoint, Compressed, Offline, NotContentIndexed, Encrypted, IntegrityStream, NoScrubData
Get-ChildItem -Attributes Hidden
ls -Attributes a  # 显示指定属性的文件或者目录

# 5.访问传统文件系统一样访问 PSDrive ,此次显示当前系统的已加载的证书
Get-ChildItem -Path Cert:\*
Get-ChildItem -Path Cert:\* -Recurse -CodeSigningCert # 获取具有代码签名权限的所有证书
Get-ChildItem -Path Cert:\LocalMachine\CA
  # PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\CA
  # Thumbprint                                Subject
  # FEE449EE0E3965A5246F000E87FDE2A065FD89D4  CN=Root Agency
  # D559A586669B08F46A30A133F8A9ED3D038E2EA8  OU=www.verisign.com/CPS Incorporated LIABI...
  # 109F1CAED645BB78B3EA2B94C0697C740733031C  CN=Microsoft Windows Hardware Compatibility,...

# 6.采用此Cmdlet从注册表配置单元获取注册表项
Get-ChildItem 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
Get-ChildItem -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion' -Depth 1 -Include "RUN" -Name   # Run
Get-ChildItem -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion' -Depth 1 -Include "RUN"
Get-ChildItem -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion' -Depth 1 -Include "RUN"
# 例如:获取远程桌面的开放端口。
Get-ChildItem -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\' -Depth 1 | % {$_.GetValue("PortNumber")}  # 3389
Get-ChildItem -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\' -Depth 1 |  % {$_.GetValue("PortNumber")}   # 3389
(Get-ChildItem -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\' -Depth 1 -exclude RCM -Include tcp,RDP-Tcp -Recurse -ErrorAction Continue) | % {$_.GetValue("PortNumber")}  # 一步到位但是会有警告
ls -Path "Registry::HKEY_CURRENT_USER\Remote"
dir -Path "Registry::HKEY_CURRENT_USER\Remote\1"


# 7.Dir获取的每一个注册表键(Microsoft.Win32.Registry 对象)对应下面的属性。
> $key = Dir HKCU: | Select-Object -first 1
> $key.GetType().FullName
Microsoft.Win32.RegistryKey
> $key | Get-Member -memberType *Property
> $key | Format-List ps*
  # PSPath        : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\AppEvents
  # PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER
  # PSChildName   : AppEvents
  # PSDrive       : HKCU
  # PSProvider    : Microsoft.PowerShell.Core\Registry
  # PSIsContainer : True

# 8.注册表提供程序不支持任何过滤器,但是参数-recurse,-include和 -exclude还是支持的,例如想知道注册表中的那个位置包含了“PowerShell”
Dir HKCU:, HKLM: -recurse -include *PowerShell* -ErrorAction SilentlyContinue

# 9.列出Uninstall的子键和它们的属性DisplayName与MoreInfoURL提供了一个简约版已安装程序列表(注意{}脚本块此处写法稍微有点坑爹)
# ,实是ForEach-Object可以接受三个脚本块用于管道的流模式处理,分别代表begin,process和end。
Dir hklm:\software\microsoft\windows\currentversion\uninstall |
ForEach-Object { Write-Host -ForegroundColor Yellow "Installed Products:" }{
 $values = Get-ItemProperty $_.PSPath;
 "{0:-30} {1:20}" -f $values.DisplayName, $values.MoreInfoURL
}{Write-Host -ForegroundColor Yellow "Finished!"}

Tips : Microsoft.Win32.Registry (注册表键) 对象的重要属性:

* Name 	           在注册编辑器中显示的键的路径
* Property 	       当前键的名称
* PSChildName 	   存储在键中的值的名称数组
* PSDrive 	       键的注册表根节点
* PSParentPath 	   父键
* PSPath 	         键的PowerShell路径,使用Dir可以查看该路径下键的内容
* PSProvider 	     提供程序的名称:注册表
* SubKeyCount(SKC) 子键个数
* ValueCount (VC)  键中的值个数
* PSIsContainer    总是为True

Tips : 如果你已经将路径定位到该注册表路径下,还可以使用另外一种方法获取所有值:

# 这里将”.”传递给Get-ItemProperty,当然前提条件是先得CD到目标键的路径下。
Cd HKLM:\Software\Microsoft\PowerShell\1
(Get-ItemProperty .).PID
89383-100-0001260-04309

Get-ItemProperty 命令 - 获取指定项的属性

描述: 该cmdlet获取指定项的属性。例如可以使用此cmdlet获取文件对象的LastAccessTime属性的值。

基础语法:

Get-ItemProperty [[-Name] <System.String[]>] [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [- Filter <System.String>] [-Include <System.String[]>] -LiteralPath <System.String[]> [-UseTransaction] [<CommonParameters>]

Get-ItemProperty [-Path] <System.String[]> [[-Name] <System.String[]>] [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Include <System.String[]>] [-UseTransaction] [<CommonParameters>]

基础示例:

# 1.获取有关特定目录的信息
Get-ItemProperty -Path C:\Users\WeiyiGeek
  # 目录: C:\Users
  # Mode                 LastWriteTime         Length Name
  # ----                 -------------         ------ ----
  # d-----         2021/5/22     12:33                WeiyiGeek

# 2.获取特定文件的属性
Get-ItemProperty -Path C:\Users\WeiyiGeek\test.txt | Format-List
  # 目录: C:\Users\WeiyiGeek
  # Name           : test.txt
  # Length         : 52094
  # CreationTime   : 2021/5/22 12:33:04
  # LastWriteTime  : 2021/5/22 12:34:23
  # LastAccessTime : 2021/5/22 19:49:21
  # Mode           : -a----
  # LinkType       :
  # Target         : {}
  # VersionInfo    : File:             C:\Users\WeiyiGeek\test.txt
  #                 InternalName:
  #                 OriginalFilename:
  #                 FileVersion:
  #                 FileDescription:
  #                 Product:
  #                 ProductVersion:
  #                 Debug:            False
  #                 Patched:          False
  #                 PreRelease:       False
  #                 PrivateBuild:     False
  #                 SpecialBuild:     False
  #                 Language:


# 3.显示注册表子项中注册表项的值名称和数据
PS C:\Users\WeiyiGeek> Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -ErrorAction Stop
PS C:\Users\WeiyiGeek> Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion'
  # SecurityHealth : C:\WINDOWS\system32\SecurityHealthSystray.exe
  # Sysdiag        : "C:\Program Files (x86)\Huorong\Sysdiag\bin\HipsTray.exe"
  # priPrinterTray : C:\Program Files\wpsPrinter\pritray.exe
  # RtHDVCpl       : "C:\Program Files\Realtek\Audio\HDA\RAVCpl64.exe" -s
  # RtHDVBg        : "C:\Program Files\Realtek\Audio\HDA\RAVBg64.exe" /MAXX4
  # PSPath         : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
  # PSParentPath   : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion
  # PSChildName    : Run
  # PSDrive        : HKLM
  # PSProvider     : Microsoft.PowerShell.Core\Registry
# 获取注册表子项中注册表项的值名称和数据(读取键的值但除了返回键值还返回了PS相关)
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp' -Name PortNumber 
  # PortNumber   : 3389
  # PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp
  # PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds
  # PSChildName  : tcp
  # PSProvider   : Microsoft.PowerShell.Core\Registry

# 示例获取远程桌面开放端口
(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp').PortNumber   # 3389
(Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp').PortNumber  # 3389

Tips : 此命令要求有一个名为HKLM:的PowerShell驱动器映射到注册表的”HKLM”配置单元。默认情况下,具有该名称和映射的驱动器在PowerShell中可用。或者可以使用以下替代路径指定此注册表子项的路径,该路径以提供程序名称开头后跟两个冒号(Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion)

Get-ItemPropertyValue 命令 - 获取指定项的一个或多个属性的值

基础语法:

Get-ItemPropertyValue [-Name] <System.String[]> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Include <System.String[]>] -LiteralPath <System.String[]> [-UseTransaction] [<CommonParameters>]

Get-ItemPropertyValue [[-Path] <System.String[]>] [-Name] <System.String[]> [-Credential <System.Management.Automation.PSCredential>][-Exclude <System.String[]>] [-Filter <System.String>] [-Include <System.String[]>] [-UseTransaction] [<CommonParameters>]

基础示例:

# 1.获取文件或文件夹的创建或者上次写入时间
Get-ItemPropertyValue -Path C:\Users\WeiyiGeek\test.txt -Name CreationTime,LastWriteTime
Get-ItemPropertyValue -Path C:\Users\WeiyiGeek -Name Root,CreationTime,LastWriteTime
  # Mode                 LastWriteTime         Length Name
  # ----                 -------------         ------ ----
  # d--hs-         2021/5/18     19:46                C:\
  # Name              : C:\
  # FullName          : C:\
  # Parent            :
  # Exists            : True
  # Root              : C:\
  # Extension         :
  # CreationTime      : 2019/3/19 12:37:21
  # CreationTimeUtc   : 2019/3/19 4:37:21
  # LastAccessTime    : 2021/5/22 19:59:53
  # LastAccessTimeUtc : 2021/5/22 11:59:53
  # LastWriteTime     : 2021/5/18 19:46:10
  # LastWriteTimeUtc  : 2021/5/18 11:46:10
  # Attributes        : Hidden, System, Directory
  # Mode              : d--hs-
  # BaseName          : C:\
  # Target            : {}
  # LinkType          :

# 2.获取Windows注册表提供程序中ProductID属性的值
Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name ProductID
  # 00331-10000-00001-AA535 
Get-ItemPropertyValue -Path 'Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp' -Name PortNumber  
Get-ItemPropertyValue -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name PortNumber 
# 3389

补充示例: Tips : 总结 Get-Child / Get-ChildItem / Get-ItemProperty / Get-ItemPropertyValue 在进行注册表项读取的不同;

# - 例如针对于当前系统自动启用的应用:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion
HKCU:\Software\Microsoft\Windows\CurrentVersion\Run
# - Get-Child:获取当前目标目录下键值
Get-Item -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'

# - Get-ChildItem:获取当前目标子目录下键值(所以的从Run的上一目录进行)
Get-ChildItem -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\' -Depth 1 -Include "RUN"
Get-ChildItem -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion' -Depth 1 -Include "RUN"

# - Get-ChildItem:获取当前目标目录下键值(所以必须在有键值的Run目录)其特点是可以直接获取键值属性
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion'

# - Get-ItemPropertyValue:获取当前目标目录下键的值(一步到位)
Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' -Name "SecurityHealth"
  # C:\WINDOWS\system32\SecurityHealthSystray.exe

Copy-Item 命令 - 将项目从一个位置复制到另一个位置

描述: 该 cmdlet将项从一个位置复制到同一命名空间中的另一个位置。例如它可以将文件复制到文件夹,但不能将文件复制到证书驱动器。

基础语法:

Copy-Item [[-Destination] <System.String>] [-Confirm] [-Container] [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-FromSession <System.Management.Automation.Runspaces.PSSession>] [-Include <System.String[]>] -LiteralPath <System.String[]> [-PassThru] [-Recurse] [-ToSession <System.Management.Automation.Runspaces.PSSession>] [-UseTransaction] [-WhatIf] [<CommonParameters>]

Copy-Item [-Path] <System.String[]> [[-Destination] <System.String>] [-Confirm] [-Container] [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-FromSession <System.Management.Automation.Runspaces.PSSession>] [-Include <System.String[]>] [-PassThru] [-Recurse] [-ToSession <System.Management.Automation.Runspaces.PSSession>] [-UseTransaction] [-WhatIf] [<CommonParameters>]

基础示例:

# 1.将文件复制到指定目录和将目录内容复制到现有目录
Copy-Item "C:\weiyigeek\mar1604.log.txt" -Destination "C:\target"
Copy-Item -Path "C:\WeiyiGeek\*" -Destination "C:\target" -Recurse
# Tips: 如果需要在副本中包含WeiyiGeek目录并将目录和内容复制到新目录,请从路径中删除\*。例如:
Copy-Item -Path "C:\WeiyiGeek" -Destination "C:\target\Logs" -Recurse

# 2.复制本地文件目录到远程主机之中
# 例如将本机的1.txt复制到远程172.16.158.183主机的之中并重命名该文件
$session = New-PSSession -ComputerName 172.16.158.183
Copy-Item -ToSession $session -Path C:\1.txt -Destination c:\2.txt
# 例如将本机的WeiyiGeek目录复制到远程172.16.158.183主机的c:\remote\WeiyiGeek之中
Copy-Item -ToSession $Session -Path "D:\WeiyiGeek\" -Destination "C:\remote\" 
# 例如递归地将本机的WeiyiGeek文件夹的全部内容复制到远程计算机
Copy-Item -ToSession $Session -Path "D:\WeiyiGeek\" -Destination "C:\remote\" -Recurse

# 3.将远程文件复制到本地计算机
# 例如将test.log从远程C:\MyRemoteData\复制到本地D:\MyLocalData文件夹原始文件未被删除。
Copy-Item -FromSession $Session  "C:\MyRemoteData\test.log" -Destination "D:\MyLocalData" 
# 例如将远程文件夹的全部内容复制到本地计算机
Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\\" -FromSession $Session
# 例如递归地将远程文件夹的全部内容复制到本地计算机
Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\scripts" -FromSession $Session -Recurse


# 4.递归地将文件从文件夹树复制到当前文件夹
PS C:\temp\test> (Get-ChildItem C:\temp\tree -Recurse).FullName
  # C:\temp\tree\subfolder
  # C:\temp\tree\file1.txt
  # C:\temp\tree\file2.txt
  # C:\temp\tree\file3.txt
  # C:\temp\tree\subfolder\file3.txt
  # C:\temp\tree\subfolder\file4.txt
  # C:\temp\tree\subfolder\file5.txt
PS C:\temp\test> Get-Content C:\temp\tree\file3.txt  # This is file3.txt in the root folder
PS C:\temp\test> Get-Content C:\temp\tree\subfolder\file3.txt  # This is file3.txt in the subfolder
PS C:\temp\test> Copy-Item -Path C:\temp\tree -Filter *.txt -Recurse -Container:$false
PS C:\temp\test> (Get-ChildItem . -Recurse).FullName
  # C:\temp\test\subfolder
  # C:\temp\test\file1.txt
  # C:\temp\test\file2.txt
  # C:\temp\test\file3.txt
  # C:\temp\test\file4.txt
  # C:\temp\test\file5.txt
PS C:\temp\test> Get-Content .\file3.txt  # This is file3.txt in the subfolder

Tips : Copy-Item cmdlet的容器参数设置为$false, 此时会导致复制源文件夹的内容但不会保留文件夹结构。请注意具有相同名称的文件将在目标文件夹中被覆盖。

Copy-ItemProperty 命令 - 将属性和值从指定位置复制到另一个位置。

描述: 描述 cmdlet将属性和值从指定位置复制到另一个位置。例如,可以使用此cmdlet将一个或多个注册表项从一个注册表项复制到另一个注册表项。

基础语法:

Copy-ItemProperty [-Destination] <System.String> [-Name] <System.String> [-Credential <System.Management.Automation.PSCredential>] [-E
xclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String[]> [-PassThru] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

Copy-ItemProperty [-Path] <System.String[]> [-Destination] <System.String> [-Name] <System.String> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] [-PassThru] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

基础示例:

# 示例1:将属性从一个注册表项复制到另一个注册表项
# 此命令将名为“MyProperty”的属性从“MyApplication”注册表项复制到“MyApplicationRev2”注册表项。
Copy-ItemProperty -Path "MyApplication" -Destination "HKLM:\Software\MyApplicationRev2" -Name "MyProperty"

New-Item 命令 - 创建一个新的项目

New-ItemProperty 命令 - 为项创建新属性并设置其值。

描述: md 命令是New-Item 命令别名.

基础语法:

New-Item [[-Path] <System.String[]>] [-Credential <System.Management.Automation.PSCredential>] [-Force] [-ItemType <System.String>] -Name <System.String> [-UseTransaction] [-Value <System.Object>] [-Confirm] [-WhatIf] [<CommonParameters>]

New-ItemProperty  [-Path] <System.String[]> [-Name] <System.String> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String[]> [-PropertyType <System.String>] [-UseTransaction] [-Value <System.Object>] [-Confirm] [-WhatIf] [<CommonParameters>]

基础示例:

# 1.创建文件(C:\temp\New Folder)和文件夹(C:\temp\New Folder\file.txt)并写入文件
New-Item -Path 'C:\temp\New Folder' -ItemType Directory
New-Item -Path 'C:\temp\New Folder\file.txt' -ItemType File -Value "This is a text string." -Force

# 2.创建注册表项以及多级目录创建
md "HKCU:\Software\First key\Second key" | Out-Null
New-Item -Path "HKLM:\Software\WeiyiGeek" 
New-Item -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WeiyiGeek\test\1" -Force
# 使用-itemType 和 -value 参数给你新创建的键来赋一个新值。
New-Item -Path "HKCU:\Software\Testkey" -itemType String -value "WeiyiGeek" | 

# 3.添加注册表项中的键值
Get-Item -Path "HKLM:\Software\WeiyiGeek\test" | New-ItemProperty -Name NoOfLocations -Value 3 -PropertyType String
New-ItemProperty -Path "HKLM:\Software\WeiyiGeek\test" -Name NoOfLocations -Value 3 -PropertyType
  # NoOfLocations : 3
  # PSPath        : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\WeiyiGeek\test
  # PSParentPath  : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\WeiyiGeek
  # PSChildName   : test
  # PSProvider    : Microsoft.PowerShell.Core\Registry

# 4.使用Here字符串在注册表中创建多字符串值
$newValue = New-ItemProperty -Path "HKLM:\SOFTWARE\WeiyiGeek\test" -Name 'HereString' -PropertyType MultiString -Value @"
This is text which contains newlines
It can also contain "quoted" strings
"@
Get-ItemProperty -Path "HKLM:\SOFTWARE\WeiyiGeek\test"  -Name HereString
$newValue.HereString
# HereString   : {This is text which contains newlines
#                It can also contain "quoted" strings}

# 5.使用数组在注册表中创建多字符串值。
$newValue = New-ItemProperty -Path "HKLM:\SOFTWARE\WeiyiGeek\test" -Name 'MultiString' -PropertyType MultiString -Value ('a','b','c')
$newValue.multistring[0]  # a

# 6.测试注册表项中各种类型键值的创建(向注册表中写入多种类型的值)
$testKey ='HKCU:\Software\Testkey'
if ( -not (Test-Path $testKey)) { md $testKey }
New-ItemProperty $testKey -name "Entry2" -value "123" -propertyType dword
New-ItemProperty $testKey Entry3 -value "Windows is in %windir%" -propertyType string
New-ItemProperty $testKey Entry4 -value "Windows is in %windir%" -propertyType expandstring
New-ItemProperty $testKey Entry5 -value "One","Two","Three" -propertyType multistring
New-ItemProperty $testKey Entry6 -value 1,2,3,4,5 -propertyType binary
New-ItemProperty $testKey Entry7 -value 100 -propertyType dword
New-ItemProperty $testKey Entry8 -value 100 -propertyType qword

WeiyiGeek.向注册表中写入多种类型的值

Tips: New-Item 命令来创建文件夹时,如果对已存在的文件使用 New-Item -Force,此文件会被完全覆盖。

Tips: 下面的表格列出所有支持的注册表值类型-itemType/-PropertyType

# ItemType 	    描述 	数据类型
String      	#一个字符串 	REG_SZ
ExpandString 	#包含环境变量的字符串在执行时可以自动处理 REG_EXPAND_SZ
Binary 	      #二进制值 	REG_BINARY
DWord 	      #32位数值 	REG_DWORD
MultiString 	#多行文本 	REG_MULTI_SZ
QWord       	#64位数值 	REG_QWORD

Tips : 我们还可以通过Microsoft.Win32.Registry对象的SetValue()GetValue()方法来读写值。(但是需要注意SetValue()方法只对刚创建的键有效,因为添加新键时PowerShell会以写权限打开它。但是对于已存在的键使用Get-Item是以只读模式打开,不能在这种情况下使用SetValue()。)

# 创建一个包含多个值的键:
$key = md HKCU:\Software\Testkey
$key.SetValue("Entry1", "123")
$key.SetValue("Entry2", "123", "Dword")
$key.SetValue("Entry3", "%windir%", "ExpandString")
$key.GetValue("Entry3")  # C:\WINDOWSWindows 会在程序读取该值之前自动解析包含在其中的处理环境变量

Tips : 非常不建议使用(Get-ItemProperty HKCU:\Software\Testkey).Entry3此种方法取值,虽然貌似简练,可读性强,但事实上它先得读取所有值效率稍低。

Set-Item 命令 - 将项的值更改为命令中指定的值

Set-ItemProperty 命令 - 创建或更改项目属性的值

基础语法:

Set-Item [-Path] <System.String[]> [[-Value] <System.Object>] [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String[]> [-PassThru] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

Set-ItemProperty ([-Name] <System.String> [-Value] <Object> } [-Path] <System.String[]>) [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -InputObject <System.Management.Automation.PSObject> [-PassThru] [-Type <RegistryValueKind>] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

基础示例:

# 1.创建运行程序别名
Set-Item -Path alias:np -Value "c:\windows\notepad.exe"
PS C:\> np demo.txt

# 2.更改环境变量的值
Set-Item -Path env:UserRole -Value "Administrator"
PS C:\> Set-Item -Path function:prompt -Value {'PS '+ (Get-Date -Format t) + " " + (Get-Location) + '> '}  # 重修改提示功能
PS 14:14 C:\>
Set-Item -Path function:prompt -Options "AllScope,ReadOnly"  # 设置提示功能的选项

# 3.设置文件的只读属性(常规与Pipeline通道)
Set-ItemProperty -Path C:\weiyigeek.doc -Name IsReadOnly -Value $true
Get-ChildItem weiyigeek.doc | Set-ItemProperty -Name IsReadOnly -Value $True

# 4.创建不存在的键值或者修改已存在的注册表键值
set-ItemProperty -Path "HKLM:\SOFTWARE\WeiyiGeek\test" -Name "NoOfEmployees" -Value 824  # 键添加值
Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\WeiyiGeek\test" -Name "NoOfEmployees" # 824
set-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WeiyiGeek\test" -Name "NoOfEmployees" -Value 1024 # 取而代之
Get-ItemPropertyValue -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WeiyiGeek\test" -Name "NoOfEmployees" # 1024

Rename-Item 命令 - 重命名PowerShell提供程序命名空间中的项

Rename-ItemProperty 命令 - 清除属性的值但不删除该属性

基础语法:

Rename-Item [-Path] <System.String> [-NewName] <System.String> [-Credential <System.Management.Automation.PSCredential>] [-Force] -LiteralPath <System.String> [-PassThru] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

Rename-ItemProperty [-Path] <System.String> [-Name] <System.String> [-NewName] <System.String> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String> [-PassThru] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

基础示例:

# 1.重命名文件(注意不能移动该文件)
Rename-Item -Path "c:\logfiles\1.txt" -NewName "2.txt"
Rename-Item -Path "project.txt" -NewName "d:\archive\old-project.txt"  # 会报错需使用 Move-Item 命令

# 2.批量重命令将后缀为.txt得文件重名为.log结尾得文件(可以采用正则匹配元组来设置重命名得名称-思路值得学习)
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '.txt','.log' }
dir | where { $_.Name -match '_\d{4}\D' } | rename-item -NewName { $_.Name -replace '.txt','.log' }  # 检查是否是需要重命名文件(进行筛选)

# 3.注册表项或者键重命名
Rename-Item -Path "HKLM:\Software\test" -NewName "Marketing"  # 此处为test目录项
Rename-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Marketing' -Name id -NewName sid  # 此处为id键命重命名为sid

Clear-Item 命令 - 清除项目的内容但不删除该项目

Clear-ItemProperty 命令 - 清除属性的值但不删除该属性

基础语法:

Clear-Item [-Path] <System.String[]> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String[]> [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

Clear-ItemProperty [-Path] <System.String[]> [-Name] <System.String> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String[]> [-PassThru] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

基础示例:

# 1.清理指定TestVar变量的值
# 方式1
Clear-Item Variable:TestVar
# 方式2
Set-Location Variable:
PS Variable:\> Clear-Item TestVar

# 2.清除SOFTWARE\WeiyiGeek\test\1下的所有注册表项
Clear-Item -Path "HKLM:\SOFTWARE\WeiyiGeek\test\1" -Confirm
Clear-Item -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WeiyiGeek\test\1" -Confirm

# 3.清除指定注册表项的值
Clear-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WeiyiGeek\test" -Name NoOfEmployees
Get-ItemPropertyValue -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WeiyiGeek\test" -Name NoOfEmployees  # 0

Remove-Item 命令 - 将项的值更改为命令中指定的值。

Remove-ItemProperty 命令 - 设置键的值

描述: del 是Remove-Item的别名.

基础语法:

Remove-Item [-Path] <System.String[]> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String[]> [-Recurse] [-Stream <System.String[]>] [-UseTransaction] [-Confirm] [-WhatIf] [<CommonParameters>]

Remove-ItemProperty [-Path] <System.String[]> [-Name] <System.String[]> [-Credential <System.Management.Automation.PSCredential>] [-Exclude <System.String[]>] [-Filter <System.String>] [-Force] [-Include <System.String[]>] -LiteralPath <System.String[]> [-UseTransaction] [-Confirm] [-WhatIf][<CommonParameters>]

基础示例:

# 1.删除具有任何文件扩展名的文件
Remove-Item C:\Test\*.* # == Del C:\Test\*.*
Remove-Item -Path C:\Test\file.txt -Force 

# 2.删除特殊条件的文件或者目录
Remove-Item -Path C:\temp\DeleteMe -Recurse # 递归删除子文件夹中的文件
Get-ChildItem * -Include *.csv -Recurse | Remove-Item # 递归删除子文件夹中的文件

Remove-Item * -Include *.doc -Exclude *1          # 删除文件夹中的某些文档文件
Get-ChildItem * -Attributes Hidden | Remove-Item  # 删除隐藏的只读文件 指定条件 ReadOnly, Hidden, System, Directory, Archive, Device, Normal, Temporary, SparseFile, ReparsePoint, Compressed, Offline, NotContentIndexed, Encrypted, IntegrityStream, NoScrubData
Get-ChildItem | Where-Object Name -Like '*`[*' | ForEach-Object { Remove-Item -LiteralPath $_.Name } # 删除带有特殊字符的文件

# 3.删除备用数据流
Get-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier
  # FileName: \\C:\Test\Copy-Script.ps1
  # Stream                   Length
  # ------                   ------
  # Zone.Identifier              26
Remove-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier
Get-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier

# 4.删除注册表值和递归删除子键(删除1注册表项以及其包含的子项)
Remove-Item 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WeiyiGeek\test\1' -Recurse
Remove-Item 'HKLM:\SOFTWARE\WeiyiGeek\test\1' -Recurse
# 删除注册表中NoOfEmployees与值
Remove-ItemProperty -Path "HKLM:\SOFTWARE\WeiyiGeek\test" -Name "NoOfEmployees"  
Get-Item -Path "HKLM:\SOFTWARE\WeiyiGeek\test" | Remove-ItemProperty -Name "NoOfEmployees"
# 从HKCU位置采用del别名删除注册表值
Set-Location HKCU:\Software\MyCompany\MyApp 
PS HKCU:\Software\MyCompany\MyApp> Del -Path . -Name "Options" -Confirm

0x02 文件内容处理

*-Content - 文本处理

相关命令:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Add-Content                                        3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Clear-Content                                      3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Get-Content                                        3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Set-Content                                        3.1.0.0    Microsoft.PowerShell.Management

Get-Content 命令 - 获取位于指定位置的项的内容

描述: 打开文本文件它的别名有cat以及Type(与Linux中的命令相似)等其获取位于指定位置的项的内容;

语法参数:

# 语法
Get-Content
  [-ReadCount <Int64>]
  [-TotalCount <Int64>]
  [-Tail <Int32>]
  [-Path] <String[]>
  [-Filter <String>]
  [-Include <String[]>]
  [-Exclude <String[]>]
  [-Force]
  [-Credential <PSCredential>]
  [-Delimiter <String>]
  [-Wait]
  [-Raw]
  [-Encoding <Encoding>]
  [-AsByteStream]
  [-Stream <String>]
  # -LiteralPath <String[]>
  [<CommonParameters>]

基础实例:

# 0.将文本文件数据读取到数组中,其中每行文件内容为一个元素.
Get-Content -Path C:\boot.ini
(Get-Content -Path C:\boot.ini).Length  # 6

# 1.打开一个文本文件test.txt读取指定数目的行数
1..100 | ForEach-Object { Add-Content -Path .\LineNumbers.txt -Value "This is line $_." }
Get-Content .\LineNumbers.txt  -TotalCount 5
  # This is Line 1
  # This is Line 2
  # This is Line 3
  # This is Line 4
  # This is Line 5

# 2.从文本文件中获取特定的内容行,TotalCount参数获取前25行内容按[-n]获取倒数第n行的数据
(Get-Content -Path .\LineNumbers.txt -TotalCount 25)[-1]
  # This is Line 25


# 3.获取文本文件的最后一行
Get-Content .\LineNumbers.txt -Tail 1
Get-Item -Path .\LineNumbers.txt | Get-Content -Tail 1
  # This is Line 100


# 4.本例中的命令将文件的内容获取为一个字符串而不是字符串数组。默认情况下如果没有原始动态参数,内容将以换行分隔字符串数组的形式返回。
$raw = Get-Content -Path .\LineNumbers.txt -Raw   # 一行显示全部内容
$lines = Get-Content -Path .\LineNumbers.txt      # 以换行符为分隔显示内容
Write-Host "Raw contains $($raw.Count) lines."
Write-Host "Lines contains $($lines.Count) lines."
  # Raw contains 1 lines.
  # Lines contains 100 lines.


# 5.以下命令获取C:\Temp目录中所有*.log文件的内容。
Get-Content -Path C:\Temp\* -Filter *.log

# 6.以字节数组形式获取文件内容
$byteArray = Get-Content -Path C:\temp\test.txt -AsByteStream -Raw
Get-Member -InputObject $bytearray
  # TypeName: System.Byte[]
  # Name           MemberType            Definition
  # ----           ----------            ----------
  # Count          AliasProperty         Count = Length
  # Add            Method                int IList.Add(System.Object value)

# 7.获取备用数据流的内容
# 检索主数据流或$数据流的内容。
Set-Content -Path .\Stream.txt -Value 'This is the content of the Stream.txt file'
Get-Content -Path .\Stream.txt -Stream $DATA # This is the content of the Stream.txt file
# 使用addcontent的Stream参数创建一个包含示例内容的新流。
Add-Content -Path .\Stream.txt -Stream NewStream -Value 'Added a stream named NewStream to Stream.txt'
# 检索新创建的流的内容。
Get-Content -Path .\Stream.txt -Stream NewStream  # Added a stream named NewStream to Stream.txt

Tips : Stream参数是文件系统提供程序的动态参数。默认情况下 Get Content只从默认值中检索数据或者:$data stream。流可用于存储隐藏的数据,如属性、安全设置或其他数据。它们也可以存储在目录中,而不是子项。

Set-Content 命令 -写入新内容或替换文件中的现有内容。

描述: Set-Content是一个字符串处理cmdlet,用于写入新内容或替换文件中的内容。要向Set-Content您发送内容,可以在命令行上使用Value参数,也可以通过管道发送内容。

基础语法:

Set-Content
  [-Path] <string[]>
  [-Value] <Object[]>
  [-PassThru]
  [-Filter <string>]
  [-Include <string[]>]
  [-Exclude <string[]>]
  [-Force]
  [-Credential <pscredential>]
  [-WhatIf]
  [-Confirm]
  [-NoNewline]
  [-Encoding <Encoding>]
  [-AsByteStream]
  [-Stream <string>]
  [<CommonParameters>]

基础案例:

# 示例1.替换当前目录中多个文件的内容。
Get-ChildItem -Path .\Test*.txt  # Test1.txt
Set-Content -Path .\Test*.txt -Value 'Hello, World'
Get-Content -Path .\Test*.txt    # Hello, World

# 示例2.创建一个新文件,并将当前日期和时间写入该文件。
Set-Content -Path .\DateTime.txt -Value (Get-Date) # 1/30/2019 09:55:08

# 示例3.替换现有文件中所有word实例。
(Get-Content -Path .\Notice.txt) |
    ForEach-Object {$_ -Replace 'Warning', 'Caution'} |
        Set-Content -Path .\Notice.txt

# 示例4.将过滤器与集合内容一起使用
# 使用过滤器限定Path 参数时,您需要在其后加上星号(*)来指示路径的内容。
Set-Content -Path C:\Temp\* -Filter *.txt -Value "Empty"

# 示例5.指定内容的备用数据流如果流不存在则此cmdlet会创建它不支持通配符。
Stream是FileSystem提供程序添加到的动态参数Set-Content。
# 此参数仅在文件系统驱动器中起作用。
# 此参数仅在Windows上可用。
PS C:\Users\WeiyiGeek> Set-Content .\LineNumbers.txt -Stream "newstream" -Value "Whoami"
PS C:\Users\WeiyiGeek> Get-Content .\LineNumbers.txt
PS C:\Users\WeiyiGeek> Get-Content .\LineNumbers.txt -Stream "newstream"
Whoami

Add-Content - 命令 将内容添加到指定的项目

描述: 该Add-Contentcmdlet将内容附加到指定的项目或文件。您可以通过在命令中键入内容或指定包含该内容的对象来指定内容。

基础语法:

Add-Content
   [-Path] <string[]>
   [-Value] <Object[]>
   [-PassThru]
   [-Filter <string>]
   [-Include <string[]>]
   [-Exclude <string[]>]
   [-Force]
   [-Credential <pscredential>]
   [-WhatIf]
   [-Confirm]
   [-NoNewline]
   [-Encoding <Encoding>]
   [-AsByteStream]
   [-Stream <string>]
   [<CommonParameters>]

基础示例:

# 1.指定文件文本内容添加
PS C:\Users\WeiyiGeek> Add-Content -Path .\LineNumbers.txt -Value "WeiyiGeek" 
PS C:\Users\WeiyiGeek> Add-Content .\LineNumbers.txt -Value (Get-Date) -PassThru
2021/3/29 12:48:22
PS C:\Users\WeiyiGeek> cat .\LineNumbers.txt
WeiyiGeek
2021/3/29 12:48:22


# 2.文件流数据添加与查看
Add-Content .\LineNumbers.txt -Stream addcontent -Value "PowerSheel"
Add-Content .\LineNumbers.txt -Stream addcontent -Value "PowerShell"
> cat .\LineNumbers.txt -Stream addcontent
PowerSheel
PowerShell


# 3.过滤器与通配符的使用
# 将值附加到当前目录中的文本文件,但根据文件名排除文件。
Add-Content -Path .\*.txt -Exclude help* -Value 'End of file'
# 命令*.txt在C:\Temp 目录中所有文件的内容后添加单词“完成” 。
Add-Content -Path C:\Temp\* -Filter *.txt -Value "Done"


# 4.将指定文件的内容添加到另一个文件(示例从文件获取内容,并将内容存储在变量中)
# 方式1.变量形式
$From = Get-Content -Path .\CopyFromFile.txt
Add-Content -Path .\CopyToFile.txt -Value $From
Get-Content -Path .\CopyToFile.txt

# 方式2.管道符模式
Get-Content -Path .\CopyFromFile.txt | Add-Content -Path .\CopyToFile.txt
Get-Content -Path .\CopyToFile.txt

# 方式3.创建一个新文,并将现有文件的内容复制到新文件中。
Add-Content -Path .\NewFile.txt -Value (Get-Content -Path .\CopyFromFile.txt)
Get-Content -Path .\NewFile.txt

# 5.即使IsReadOnly文件属性设置为True,此命令也会向文件添加一个值。
Add-Content -Path .\IsReadOnlyTextFile.txt -Value 'Add value to read-only text file' -Force

Clear-Content 命令 - 删除(清空)项目的内容

描述: 该Clear-Contentcmdlet删除项目的内容,例如从文件中删除文本但不会删除该项目。

Tips : 在 Clear-Content 类似 Clear-Item 但它对有内容的项目有效,而不是有值的项目。

基础语法:

Clear-Content
     [-Path] <String[]>
     [-Filter <String>]
     [-Include <String[]>]
     [-Exclude <String[]>]
     [-Force]
     [-Credential <PSCredential>]
     [-WhatIf]
     [-Confirm]
     [-Stream <String>]
     [<CommonParameters>]

基础示例:

# 示例1:从目录中删除有init.txt文件的所有内容
Clear-Content "..\SmpUsers\*\init.txt"

# 示例2:使用通配符删除所有文件的内容
Clear-Content -Path "*" -Filter "*.log" -Force

# 示例3:清除指定流(Stream)中的所有数据
PS C:\Users\WeiyiGeek> Get-Content .\LineNumbers.txt -Stream "newstream"
  # Whoami
PS C:\Users\WeiyiGeek> Clear-Content .\LineNumbers.txt -Stream newstream
PS C:\Users\WeiyiGeek> Get-Content .\LineNumbers.txt -Stream "newstream"


文件识别校验

Get-FileHash 命令 - 文件校验与识别

描述: PowerShell命令校验文件的Hash值(MD5、SHA1/256、MACTripleDES、RIPEMD160等)

类型 & 语法

> (Get-Command *-FileHash)
CommandType     Name               Version    Source
-----------     ----               -------    ------
Function        Get-FileHash       3.1.0.0    Microsoft.PowerShell.Utility

# 命令格式
Get-FileHash 文件路径 -Algorithm 校验的Hash值类型 | Format-List
# 校验的Hash值类型包括:SHA1、SHA256、SHA384、SHA512、MACTripleDES、MD5、RIPEMD160,暂不支持校验CRC32值。

基础示例:

# 1) 以验证系统的记事本程序的Hash值为例
> Get-FileHash C:\Windows\notepad.exe -Algorithm MD5
Algorithm       Hash   Path
---------       ----   ----
MD5             423D3ADE2F14572C5BD5F546973EB493       C:\Windows\notepad.exe

# 2) 以数列格式显示
> Get-FileHash C:\Windows\notepad.exe -Algorithm SHA1 | Format-List
Algorithm : SHA1
Hash      : A1F446D0C29913D3F863BA164EFE86B6E9E5E7FF
Path      : C:\Windows\notepad.exe


# 3) 只显示某项值
(Get-FileHash C:\Windows\notepad.exe -Algorithm SHA1).Hash
A1F446D0C29913D3F863BA164EFE86B6E9E5E7FF

0x04 文件目录解压缩

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/"

实用案例:

示例1.将某一个目录和数字目录下的所有的pdf单个压缩到指定目录并按照数字目录进行存储。

$SRC="H:\WeiyiGeek\SRC\"
$DEST="H:\WeiyiGeek\DEST\"
foreach ($PDFNAME in (Get-ChildItem $SRC -Filter "*.pdf" -Recurse).FullName ) {
  $Temp_name = "$PDFNAME".Split("\")
  $Temp_dest = $Temp_name[-2]+"\"+$Temp_name[-1].Split(".")[0]+".zip"
  Write-Host "正在压缩 ${DEST} ${Temp_dest};"
  Compress-Archive -Path "$PDFNAME" -DestinationPath "${DEST}${Temp_dest}"
}

示例2.验证并利用正则提取文件中的身份证号并作为目标文件名称,匹配失败的写入指定的错误文件之中。

$SRC="F:\src\"
$DEST="F:\dest\"
$ERRFILE="F:\error.txt"
mkdir $DEST
foreach ($PDFNAME in (Get-ChildItem $SRC -Filter "*.pdf" -Recurse).FullName ) {
  if ($PDFNAME -match '(?<id>([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx])') {
    $PDFDEST = $DEST + $Matches.id + ".pdf"
    Write-Host "$PDFNAME  -> $PDFDEST"
    $PDFSRC = [Management.Automation.WildcardPattern]::Escape($PDFNAME)
    Copy-Item -Path "$PDFSRC" -Destination "$PDFDEST" -Force
  }else {
    Write-Output "$PDFNAME"
    Write-Output "$PDFNAME" | Out-File -FilePath $ERRFILE
  }
}

温馨提示: 由于Powershell默认无法处理带有[或者]符号的文件名称,我们需要将源目录利用[Management.Automation.WildcardPattern]::Escape($PDFNAME)命令进行编码使用。


0x05 特定数据输出

Tee-Object 命令 - 将输出保存在文件或变量中并沿管道发送。

描述: 该cmdlet的作用是重定向输出,即它以两个方向(如字母T)发送命令的输出,它将输出存储在文件或变量中并可以通过管道发送。如果Tee对象是管道中的最后一个命令,则命令输出将显示在提示处(类似于Linux中的tee命令)。

语法参数:

Tee-Object
  [-InputObject <PSObject>]
  [-FilePath] <String>
  [-Append]
  [<CommonParameters>]

Tee-Object
  [-InputObject <PSObject>]
  -LiteralPath <String> | -Variable <String>
  [<CommonParameters>]

# 参数:
-Append : 指示cmdlet将输出附加到指定的文件,如果没有此参数,新内容将替换文件中的任何现有内容,而不会发出警告。
-FilePath : 指定此cmdlet将对象保存为允许使用通配符但必须解析为单个文件的文件。

基础示例:

# 1.示例1:将进程输出到文件和控制台
PS C:\Users\WeiyiGeek\ps> Get-Process | Tee-Object -FilePath "process.txt"
  # Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
  # -------  ------    -----      -----     ------     --  -- -----------
  #     662      40    22964      32464   2,700.95   7200   1 ApplicationFrameHost
dir
  # 目录: C:\Users\WeiyiGeek\ps
  # Mode                 LastWriteTime         Length Name
  # ----                 -------------         ------ ----
  # -a----         2021/4/29     17:28          66542 process.txt

Get-Process explorer | Tee-Object -Variable proc | Select-Object processname,handles
# 2.示例2:将进程输出到变量和“Select Object”`管道的应用
PS C:\Users\WeiyiGeek\ps> Get-Process explorer | Tee-Object -Variable proc
PS C:\Users\WeiyiGeek\ps> $proc
  # Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
  # -------  ------    -----      -----     ------     --  -- -----------
  #   16220     601   455952     241664  42,431.52   7408   1 explorer
  #   1619      85   102336      67632     981.56  17544   1 explorer
PS C:\Users\WeiyiGeek\ps> Get-Process explorer | Tee-Object -Variable proc | Select-Object processname,handles

# 3.此示例将系统文件列表保存在两个日志文件中,一个是累积文件另一个是当前文件。
Get-ChildItem -Path D: -File -System -Recurse |
  Tee-Object -FilePath ".\AllSystemFiles.txt" -Append |
    Out-File .\NewSystemFiles.txt

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

0x0n 技巧总结

1.PS操作注册表的重要命令

描述: 下面的表格列出了访问注册表所需的所有命令。

  • Test-Path:验证键是否存在
  • Cd, Set-Location: 更改当前(键)目录
  • Dir,ls, Get-ChildItem: 列出键的内容
  • Get-ItemProperty: 读取键的值
  • Set-ItemProperty: 设置键的值
  • md, New-Item : 创建一个新键(项)
  • Del, Remove-Item : 删除一个键(项)
  • New-ItemProperty : 给键创建一个新值
  • Clear-ItemProperty : 删除键的值内容
  • Remove-ItemProperty : 删除键的值

Tips:注册表几乎存储了Windows的核心配置。所以这也是它为什么成为我们用来读取和更改Windows配置的重要位置,因此乱搞或者误删非常危险可能造成Windows不能启动。 Tips: HKCU:, HKLM:预定义的两个重要注册表根目录虚拟驱动器或者不使用预定义的情况registry::来指定注册表的全路径。