Skip to main content

PowerShell在Windows Server Core上处理文件的技巧

分类:  PowerShell 标签:  #基础 #Windows Server Core #Windows #脚本编程 发布于: 2023-08-05 17:24:30

将自己的网站转为使用Windows Server Core 2022作为基础的系统之后,需要通过命令行对系统进行管理,特别是对于文件系统的管理,例如查询文件,列出文件, 查看文件夹或者文件的大小,删除文件夹,给用户授权等等,刚开始使用有很多不习惯的地方,这里记录一下一些使用PowerShell操作文件的小技巧。

列出文件

PowerShell下主要是使用如下几个指令来操作文件以及文件系统:

  • Get-Location
  • Set-Location
  • Get-ChildItem
  • Remove-ChildItem
  • New-item

我们接下来演示一下上述几个指令:

Get-Location

PS D:\MyProjects\mydocuments> Get-Alias -Name gl

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           gl -> Get-Location

PS D:\MyProjects\mydocuments> Get-Alias -Name pwd

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           pwd -> Get-Location

首先检查一下Get-Location的别名,分别包括:glpwd

该指令主要返回当前的路径:

PS D:\MyProjects\mydocuments> Get-Location

Path
----
D:\MyProjects\mydocuments

Set-Location

help set-location

ALIASES
    sl
    cd
    chdir

PS D:\MyProjects\mydocuments> Get-Alias -Name sl

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           sl -> Set-Location

PS D:\MyProjects\mydocuments> Get-Alias -Name cd

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cd -> Set-Location

PS D:\MyProjects\mydocuments> Get-Alias -Name chdir

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           chdir -> Set-Location

该指令的主要功能就和它的别名是一致的:

PS D:\MyProjects\mydocuments> cd -Path C:\Windows\System32\inetsrv\
PS C:\Windows\System32\inetsrv> set-location -Path C:\windows\system32\inetsrv\
PS C:\Windows\System32\inetsrv> sl -Path C:\windows\system32\inetsrv\
PS C:\Windows\System32\inetsrv> Get-location

Path
----
C:\Windows\System32\inetsrv

Get-ChildItem

help get-childitem

ALIASES
    gci
    ls
    dir

PS C:\> Get-Alias -Name ls

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ls -> Get-ChildItem

PS C:\> Get-Alias -Name gci

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           gci -> Get-ChildItem

PS C:\> Get-Alias -Name dir

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           dir -> Get-ChildItem

这个指令的作用也可以从别名中看出来了。但是这个指令有两个参数: -Force和 -Recurse

  • -Force: 强制限制隐藏或者系统文件
  • -Recurse: 递归限制目录下所有的子目录或者文件.
PS C:\> Get-ChildItem -Path C:\Windows\ -Recurse

    Directory: C:\Windows

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----           2022/10/3    18:58                addins
d----           2023/7/27    10:03                appcompat
d----           2023/7/27    10:03                apppatch
d----            2023/8/3    13:13                AppReadiness
d-r--            2023/8/2    14:53                assembly
d----           2023/7/27    10:03                bcastdvr
d----            2022/5/7    13:42                Boot
d----            2022/5/7    13:24                Branding
d----            2022/5/7    18:17                BrowserCore
d----           2023/7/27     9:22                CbsTemp
d----            2022/5/7    18:28                Containers
d----           2022/1/19    16:31                CSC

Remove-Item

 help remove-item

 ALIASES
    ri
    rm
    rmdir
    del
    erase
    rd

该指令也需要注意两个指令:

  • -Force
  • -Recurse

New-Item

注意New-Item的参数-ItemType

PS C:\> New-Item -Name test.txt -ItemType File


    目录: C:\


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          2023/8/5     16:36              0 test.txt

统计文件或者文件夹的大小

使用如下的脚本统计文件夹的大小:

Get-ChildItem -Path C:\Windows\ -Recurse | Measure-Object -Sum Length | Select-Object @{name='size(mb)';expression={$_.Sum/1mb}}

      size(mb)
      --------
8851.387758255

以上脚本用于统计和计算文件夹的大小。

文件或者文件夹ntfs权限管理

我们先查看一下系统里现有的组和用户:

PS C:\> Get-LocalGroup | ft -AutoSize

Name                                Description
----                                -----------
SQLServer2005SQLBrowserUser$WWW     该组中的成员具有所需的访问权限和特权,可以被指定为 SQL Server Browser 关联实例的登录帐户。
Access Control Assistance Operators 此组的成员可以远程查询此计算机上资源的授权属性和权限。
Administrators                      管理员对计算机/域有不受限制的完全访问权
Backup Operators                    备份操作员为了备份或还原文件可以替代安全限制
Certificate Service DCOM Access     允许该组的成员连接到企业中的证书颁发机构
Cryptographic Operators             授权成员执行加密操作。
Device Owners                       此组的成员可以更改系统范围内的设置。
Distributed COM Users               成员允许启动、激活和使用此计算机上的分布式 COM 对象。
Event Log Readers                   此组的成员可以从本地计算机中读取事件日志
Guests                              按默认值,来宾跟用户组的成员有同等访问权,但来宾帐户的限制更多
Hyper-V Administrators              此组的成员拥有对 Hyper-V 所有功能的完全且不受限制的访问权限。
IIS_IUSRS                           Internet 信息服务使用的内置组。
Network Configuration Operators     此组中的成员有部分管理权限来管理网络功能的配置
Performance Log Users               该组中的成员可以计划进行性能计数器日志记录、启用跟踪记录提供程序,以及在本地或通过远程访问此计算机来收集事件跟踪记录

Performance Monitor Users           此组的成员可以从本地和远程访问性能计数器数据
Power Users                         包括高级用户以向下兼容,高级用户拥有有限的管理权限
Print Operators                     成员可以管理在域控制器上安装的打印机
RDS Endpoint Servers                此组中的服务器运行虚拟机和主机会话,用户 RemoteApp 程序和个人虚拟桌面将在这些虚拟机和会话中运行。需要将此组填充到运行 RD 连接代理的服务...
RDS Management Servers              此组中的服务器可以在运行远程桌面服务的服务器上执行例程管理操作。需要将此组填充到远程桌面服务部署中的所有服务器上。必须将运行 RDS 中心管理服务的服...
RDS Remote Access Servers           此组中的服务器使 RemoteApp 程序和个人虚拟桌面用户能够访问这些资源。在面向 Internet 的部署中,这些服务器通常部署在边缘网络中。需要...
Remote Desktop Users                此组中的成员被授予远程登录的权限
Remote Management Users             此组的成员可以通过管理协议(例如,通过 Windows 远程管理服务实现的 WS-Management)访问 WMI 资源。这仅适用于授予用户访问权限...
Replicator                          支持域中的文件复制
Storage Replica Administrators      此组的成员具有存储副本所有功能的不受限的完全访问权限。
System Managed Accounts Group       此组的成员由系统管理。
Users                               防止用户进行有意或无意的系统范围的更改,但是可以运行大部分应用程序


PS C:\>

显示本地用户

PS C:\> Get-LocalUser | ft -AutoSize

Name               Enabled Description
----               ------- -----------
Administrator      True    管理计算机()的内置帐户
DefaultAccount     False   系统管理的用户帐户。
Guest              False   供来宾访问计算机或访问域的内置帐户
WDAGUtilityAccount False   系统为 Windows Defender 应用程序防护方案管理和使用的用户帐户。

显示目前系统有的权限有哪些:

PS C:\> [System.Enum]::GetNames([System.Security.AccessControl.FileSystemRights])
ListDirectory
ReadData
WriteData
CreateFiles
CreateDirectories
AppendData
ReadExtendedAttributes
WriteExtendedAttributes
Traverse
ExecuteFile
DeleteSubdirectoriesAndFiles
ReadAttributes
WriteAttributes
Write
Delete
ReadPermissions
Read
ReadAndExecute
Modify
ChangePermissions
TakeOwnership
Synchronize
FullControl
PS C:\>

然后需要注意的是如果要对文件或者文件夹权限管理,主要要用到如下几个指令:

  • Get-ACL
  • Set-ACL
  • New-Object System.Security.Accesscontrol.FileSystemAccessRule

这里有一个对象我们需要仔细的研究一下:System.Security.Accesscontrol.FileSystemAccessRule,可以仔细参考.Net的文档:
https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemaccessrule?view=net-7.0

该文档里对于这个对象的构造函数做了很详细的说明:

FileSystemAccessRule(IdentityReference, FileSystemRights, AccessControlType)
FileSystemAccessRule(IdentityReference, FileSystemRights, InheritanceFlags, PropagationFlags, AccessControlType)
FileSystemAccessRule(String, FileSystemRights, AccessControlType)
FileSystemAccessRule(String, FileSystemRights, InheritanceFlags, PropagationFlags, AccessControlType)

这里主要看一下构造函数:FileSystemAccessRule(IdentityReference, FileSystemRights, InheritanceFlags, PropagationFlags, AccessControlType)

这里IdentityReference指的是我们的用户或者用户组
FileSystemRights: 我们刚刚已经通过[System.Enum]::GetNames([System.Security.AccessControl.FileSystemRights]) 全部列出了目前ntfs文件系统支持的所有的权限。

下面我们再列出InheritanceFlags, PropagationFlags以及 AccessControlType的可能取值。

PS C:\> [System.Enum]::GetNames([System.Security.AccessControl.InheritanceFlags])
None
ContainerInherit
ObjectInherit
PS C:\> [System.Enum]::GetNames([System.Security.AccessControl.PropagationFlags])
None
NoPropagateInherit
InheritOnly
PS C:\> [System.Enum]::GetNames([System.Security.AccessControl.AccessControlType])
Allow
Deny
PS C:\>

因此如下的是我们对于目录的授权:

PS C:\> $acl = Get-Acl -Path C:\inetpub\
PS C:\> $identity = "IIS_IUSRS"
PS C:\> $rights = 'FullControl'
PS C:\> $inheritanceFlag = 'ContainerInherit,ObjectInherit'
PS C:\> $PropagationFlag = 'InheritOnly'
PS C:\> $AccessControlType = 'Allow'
PS C:\> $AccessRules = New-Object System.Security.AccessControl.FileSystemAccessRule($identity, $rights, $inheritanceFlag, $PropagationFlag, $AccessControlType)
PS C:\> $AccessRules


FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : IIS_IUSRS
IsInherited       : False
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : InheritOnly



PS C:\> $acl.Access | Format-Table -AutoSize

           FileSystemRights AccessControlType IdentityReference           IsInherited             InheritanceFlags
           ---------------- ----------------- -----------------           -----------             ----------------
                  268435456             Allow CREATOR OWNER                     False ...nerInherit, ObjectInherit
                  268435456             Allow NT AUTHORITY\SYSTEM               False ...nerInherit, ObjectInherit
                FullControl             Allow NT AUTHORITY\SYSTEM               False                         None
                  268435456             Allow BUILTIN\Administrators            False ...nerInherit, ObjectInherit
                FullControl             Allow BUILTIN\Administrators            False                         None
                -1610612736             Allow BUILTIN\Users                     False ...nerInherit, ObjectInherit
ReadAndExecute, Synchronize             Allow BUILTIN\Users                     False                         None
                  268435456             Allow NT SERVICE\TrustedInstaller       False ...nerInherit, ObjectInherit
                FullControl             Allow NT SERVICE\TrustedInstaller       False                         None


PS C:\> $acl.AddAccessRule($AccessRules)
PS C:\> $acl.SetAccessRuleProtection($false, $false)
PS C:\> Set-Acl -Path C:\inetpub\ -AclObject $acl
PS C:\> (Get-Acl -Path C:\inetpub\).Access | Format-Table -AutoSize

           FileSystemRights AccessControlType IdentityReference           IsInherited             InheritanceFlags
           ---------------- ----------------- -----------------           -----------             ----------------
                  268435456             Allow CREATOR OWNER                     False ...nerInherit, ObjectInherit
                  268435456             Allow NT AUTHORITY\SYSTEM               False ...nerInherit, ObjectInherit
                FullControl             Allow NT AUTHORITY\SYSTEM               False                         None
                  268435456             Allow BUILTIN\Administrators            False ...nerInherit, ObjectInherit
                FullControl             Allow BUILTIN\Administrators            False                         None
                -1610612736             Allow BUILTIN\Users                     False ...nerInherit, ObjectInherit
ReadAndExecute, Synchronize             Allow BUILTIN\Users                     False                         None
                FullControl             Allow BUILTIN\IIS_IUSRS                 False ...nerInherit, ObjectInherit
                FullControl             Allow NT SERVICE\TrustedInstaller       False                         None
                  268435456             Allow NT SERVICE\TrustedInstaller       False ...nerInherit, ObjectInherit
                FullControl             Allow NT AUTHORITY\SYSTEM                True ...nerInherit, ObjectInherit
                FullControl             Allow BUILTIN\Administrators             True ...nerInherit, ObjectInherit
ReadAndExecute, Synchronize             Allow BUILTIN\Users                      True ...nerInherit, ObjectInherit
                 AppendData             Allow BUILTIN\Users                      True             ContainerInherit
                CreateFiles             Allow BUILTIN\Users                      True             ContainerInherit
                  268435456             Allow CREATOR OWNER                      True ...nerInherit, ObjectInherit


PS C:\>

以上代码完整的演示了如何进行文件和文件的权限管理全部的过程了。