# PowerShell命令大全

## 目录

- [基础命令](#基础命令)
- [系统信息查询](#系统信息查询)
- [文件和目录操作](#文件和目录操作)
- [进程和服务管理](#进程和服务管理)
- [用户和组管理](#用户和组管理)
- [网络管理](#网络管理)
- [注册表操作](#注册表操作)
- [Windows管理](#windows管理)
- [远程操作](#远程操作)
- [脚本和函数](#脚本和函数)
- [WMI/CIM操作](#wmicim操作)
- [事件日志管理](#事件日志管理)
- [磁盘和存储管理](#磁盘和存储管理)
- [安全和加密](#安全和加密)
- [常用操作符和变量](#常用操作符和变量)
- [高级功能](#高级功能)
- [示例脚本](#示例脚本)

## 基础命令

```powershell
# 查看PowerShell版本
$PSVersionTable

# 查看帮助
Get-Help
Get-Help Get-Process -Full
Get-Help *file*  # 查找包含file的命令

# 更新帮助
Update-Help -Force

# 获取命令列表
Get-Command
Get-Command -Verb Get -Noun Process
Get-Command -Module Microsoft.PowerShell.Management

# 查看别名
Get-Alias
Get-Alias -Definition Get-Process

# 创建别名
New-Alias -Name gp -Value Get-Process

# 设置执行策略
Set-ExecutionPolicy RemoteSigned
Get-ExecutionPolicy

# 历史命令
Get-History
Clear-History

# 重定向输出
Get-Process > process.txt
Get-Process | Out-File process.txt
Get-Process | Export-Csv process.csv

# 管道操作
Get-Process | Where-Object {$_.CPU -gt 10}
Get-Process | Sort-Object CPU -Descending
Get-Process | Select-Object Name, CPU -First 5
```

## 系统信息查询

```powershell
# 查看操作系统信息
Get-CimInstance Win32_OperatingSystem
Get-ComputerInfo

# 查看计算机系统信息
Get-CimInstance Win32_ComputerSystem

# 查看BIOS信息
Get-CimInstance Win32_BIOS

# 查看CPU信息
Get-CimInstance Win32_Processor

# 查看内存信息
Get-CimInstance Win32_PhysicalMemory
Get-CimInstance Win32_OperatingSystem | Select-Object TotalVisibleMemorySize, FreePhysicalMemory

# 查看磁盘信息
Get-CimInstance Win32_LogicalDisk
Get-CimInstance Win32_DiskDrive

# 查看网络适配器信息
Get-NetAdapter
Get-NetIPAddress
Get-NetRoute

# 查看启动时间
Get-CimInstance Win32_OperatingSystem | Select-Object LastBootUpTime

# 查看系统负载
Get-Counter '\Processor(_Total)\% Processor Time'
Get-Counter '\Memory\Available MBytes'
```

## 文件和目录操作

```powershell
# 列出目录内容
Get-ChildItem
Get-ChildItem -Recurse
Get-ChildItem -Hidden

# 创建目录
New-Item -ItemType Directory -Path C:\NewFolder
mkdir C:\NewFolder

# 创建文件
New-Item -ItemType File -Path C:\NewFolder\test.txt

# 复制文件/目录
Copy-Item -Path C:\Source\* -Destination C:\Destination\
Copy-Item -Path C:\Source -Destination C:\Destination -Recurse

# 移动文件/目录
Move-Item -Path C:\Source\file.txt -Destination C:\Destination\

# 删除文件/目录
Remove-Item -Path C:\file.txt
Remove-Item -Path C:\Folder -Recurse -Force

# 重命名文件/目录
Rename-Item -Path C:\oldname.txt -NewName newname.txt

# 查看文件内容
Get-Content -Path C:\file.txt
Get-Content -Path C:\file.txt -Tail 10  # 查看最后10行
Get-Content -Path C:\file.txt -Head 5   # 查看前5行

# 编辑文件内容
Set-Content -Path C:\file.txt -Value "New content"
Add-Content -Path C:\file.txt -Value "Additional content"

# 搜索文件内容
Select-String -Path C:\*.txt -Pattern "search text"

# 文件属性
Get-ItemProperty -Path C:\file.txt
Set-ItemProperty -Path C:\file.txt -Name IsReadOnly -Value $true

# 文件哈希
Get-FileHash -Path C:\file.txt -Algorithm SHA256
```

## 进程和服务管理

```powershell
# 查看进程
Get-Process
Get-Process -Name chrome*  # 查找Chrome进程
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10

# 启动进程
Start-Process -FilePath "notepad.exe"
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoExit", "-Command Get-Process"

# 终止进程
Stop-Process -Name notepad
Stop-Process -Id 1234

# 查看服务
Get-Service
Get-Service -Running  # 只查看正在运行的服务
Get-Service *network*  # 查找包含network的服务

# 启动服务
Start-Service -Name wuauserv

# 停止服务
Stop-Service -Name wuauserv

# 重启服务
Restart-Service -Name wuauserv

# 设置服务启动类型
Set-Service -Name wuauserv -StartupType Automatic
Set-Service -Name wuauserv -StartupType Disabled
```

## 用户和组管理

```powershell
# 查看本地用户
Get-LocalUser
Get-LocalUser -Name Administrator  # 查看特定用户

# 创建本地用户
New-LocalUser -Name "NewUser" -Password (Read-Host -AsSecureString) -FullName "New User" -Description "Test user"

# 修改用户密码
Set-LocalUser -Name "NewUser" -Password (Read-Host -AsSecureString)

# 禁用/启用用户
Disable-LocalUser -Name "NewUser"
Enable-LocalUser -Name "NewUser"

# 删除用户
Remove-LocalUser -Name "NewUser"

# 查看本地组
Get-LocalGroup

# 创建本地组
New-LocalGroup -Name "NewGroup" -Description "Test group"

# 查看组成员
Get-LocalGroupMember -Group "Administrators"

# 添加用户到组
Add-LocalGroupMember -Group "Administrators" -Member "NewUser"

# 从组中移除用户
Remove-LocalGroupMember -Group "Administrators" -Member "NewUser"

# 查看当前用户
$env:USERNAME
[Security.Principal.WindowsIdentity]::GetCurrent().Name
```

## 网络管理

```powershell
# 网络连接
Get-NetTCPConnection
Get-NetTCPConnection -State Established  # 查看已建立的连接
Get-NetTCPConnection -LocalPort 80       # 查看80端口的连接

# 网络适配器
Get-NetAdapter
Get-NetAdapterStatistics  # 查看网络适配器统计信息

# IP配置
Get-NetIPAddress
Get-NetIPConfiguration
Get-NetIPv4Protocol

# 设置IP地址
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.1.100" -PrefixLength 24 -DefaultGateway "192.168.1.1"

# DNS设置
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses "8.8.8.8", "8.8.4.4"
Get-DnsClientServerAddress

# 网络诊断
Test-Connection -ComputerName www.google.com -Count 4  # Ping
Test-NetConnection -ComputerName www.google.com -Port 80  # 测试端口连接

# 防火墙
Get-NetFirewallRule
New-NetFirewallRule -DisplayName "Allow Port 8080" -Direction Inbound -LocalPort 8080 -Protocol TCP -Action Allow
Disable-NetFirewallRule -DisplayName "Allow Port 8080"

# 网络共享
Get-SmbShare
New-SmbShare -Name "ShareName" -Path "C:\Share" -FullAccess "Everyone"
```

## 注册表操作

```powershell
# 查看注册表项
Get-Item -Path HKLM:\Software\Microsoft\Windows\CurrentVersion
Get-ChildItem -Path HKLM:\Software

# 创建注册表项
New-Item -Path HKLM:\Software\MyCompany

# 创建注册表值
New-ItemProperty -Path HKLM:\Software\MyCompany -Name "AppVersion" -Value "1.0" -PropertyType String

# 修改注册表值
Set-ItemProperty -Path HKLM:\Software\MyCompany -Name "AppVersion" -Value "2.0"

# 读取注册表值
Get-ItemProperty -Path HKLM:\Software\MyCompany -Name "AppVersion"

# 删除注册表值
Remove-ItemProperty -Path HKLM:\Software\MyCompany -Name "AppVersion"

# 删除注册表项
Remove-Item -Path HKLM:\Software\MyCompany -Recurse
```

## Windows管理

```powershell
# 查看已安装程序
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*
Get-Package

# 管理已安装的Windows功能
Get-WindowsFeature
Install-WindowsFeature -Name Web-Server -IncludeManagementTools
Remove-WindowsFeature -Name Web-Server

# 启动/关闭Windows功能（客户端）
Get-WindowsOptionalFeature -Online
Enable-WindowsOptionalFeature -Online -FeatureName TelnetClient
Disable-WindowsOptionalFeature -Online -FeatureName TelnetClient

# 管理任务计划
Get-ScheduledTask
New-ScheduledTask -Action (New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\script.ps1") -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date)) -TaskName "MyTask"
Register-ScheduledTask -TaskName "MyTask" -InputObject $task -User "SYSTEM"
Start-ScheduledTask -TaskName "MyTask"
Stop-ScheduledTask -TaskName "MyTask"
Unregister-ScheduledTask -TaskName "MyTask" -Confirm:$false

# 管理Windows更新
Get-WindowsUpdate  # 需要PSWindowsUpdate模块
Install-WindowsUpdate -AcceptAll -AutoReboot
```

## 远程操作

```powershell
# 远程执行命令
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process }

# 在多台计算机上执行命令
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock { Get-Service }

# 远程会话
Enter-PSSession -ComputerName Server01
Exit-PSSession

# 创建持久会话
$session = New-PSSession -ComputerName Server01
Invoke-Command -Session $session -ScriptBlock { Get-Process }
Remove-PSSession $session

# 复制文件到远程计算机
Copy-Item -Path C:\file.txt -Destination \\Server01\C$\

# 使用PSRemoting传输文件
Copy-Item -Path C:\file.txt -Destination C:\file.txt -ToSession $session
```

## 脚本和函数

```powershell
# 基本脚本结构
# PowerShell脚本文件使用.ps1扩展名

# 注释
# 这是单行注释
<#
这是多行注释
#>

# 创建函数
function Get-SystemInfo {
    param(
        [string]$ComputerName = $env:COMPUTERNAME
    )
    
    $os = Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName
    $cpu = Get-CimInstance Win32_Processor -ComputerName $ComputerName
    $mem = Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName
    
    [PSCustomObject]@{
        ComputerName = $ComputerName
        OS = $os.Caption
        BuildNumber = $os.BuildNumber
        CPU = $cpu.Name
        MemoryGB = [math]::Round(($mem | Measure-Object -Property Capacity -Sum).Sum / 1GB, 2)
    }
}

# 使用函数
Get-SystemInfo
Get-SystemInfo -ComputerName RemoteComputer

# 参数高级用法
function Test-Params {
    param(
        [Parameter(Mandatory=$true, HelpMessage="请输入名称")]
        [string]$Name,
        
        [Parameter(Mandatory=$false)]
        [int]$Age = 18,
        
        [ValidateSet("男", "女")]
        [string]$Gender
    )
    
    Write-Host "姓名: $Name"
    Write-Host "年龄: $Age"
    Write-Host "性别: $Gender"
}
```

## WMI/CIM操作

```powershell
# CIM查询（推荐）
Get-CimInstance -ClassName Win32_Process
Get-CimInstance -ClassName Win32_Service -Filter "State = 'Running'"

# WMI查询（旧版）
Get-WmiObject -Class Win32_Process

# CIM方法调用
Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine="notepad.exe"}

# 查询特定计算机
Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName RemoteComputer

# 使用WQL查询语言
Get-CimInstance -Query "SELECT * FROM Win32_Process WHERE Name LIKE '%chrome%'"

# 获取类列表
Get-CimClass -Namespace root\cimv2 | Where-Object CimClassName -like "Win32_*"
```

## 事件日志管理

```powershell
# 查看事件日志列表
Get-EventLog -List

# 查看系统日志
Get-EventLog -LogName System
Get-EventLog -LogName System -Newest 10  # 查看最新10条

# 查看应用程序日志
Get-EventLog -LogName Application -EntryType Error -Newest 10  # 查看错误日志

# 查看安全日志
Get-EventLog -LogName Security -Newest 10

# 写入事件日志
Write-EventLog -LogName Application -Source "MyScript" -EventId 1000 -EntryType Information -Message "脚本执行成功"

# 清除事件日志
Clear-EventLog -LogName System

# 使用Get-WinEvent（支持Windows事件日志）
Get-WinEvent -LogName Microsoft-Windows-Sysmon/Operational -MaxEvents 10
```

## 磁盘和存储管理

```powershell
# 查看磁盘信息
Get-PhysicalDisk
Get-Disk
Get-Partition
Get-Volume

# 查看磁盘空间
Get-PSDrive -PSProvider FileSystem
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, Size, FreeSpace

# 创建分区
Initialize-Disk -Number 1 -PartitionStyle GPT
New-Partition -DiskNumber 1 -UseMaximumSize -AssignDriveLetter
Format-Volume -DriveLetter E -FileSystem NTFS -NewFileSystemLabel "Data"

# 卷影复制
Get-WmiObject -Class Win32_ShadowCopy

# 磁盘配额
Get-FsrmQuota
```

## 安全和加密

```powershell
# 管理凭证
Get-Credential  # 创建凭证对象
$cred = Get-Credential

# 安全字符串
$secureString = ConvertTo-SecureString "Password123" -AsPlainText -Force
$plainText = ConvertFrom-SecureString $secureString

# 哈希
Get-FileHash -Path C:\file.txt -Algorithm SHA256

# 证书管理
Get-ChildItem -Path Cert:\LocalMachine\My

# 管理ACL（访问控制列表）
Get-Acl -Path C:\file.txt
$acl = Get-Acl -Path C:\file.txt
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Users", "Read", "Allow")
$acl.SetAccessRule($rule)
Set-Acl -Path C:\file.txt -AclObject $acl

# PowerShell安全
Get-ExecutionPolicy -List
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
```

## 常用操作符和变量

```powershell
# 变量
$variable = "Value"

# 数组
$array = @(1, 2, 3, 4, 5)
$array[0]  # 访问第一个元素
$array.Count  # 数组长度

# 哈希表
$hashTable = @{
    Name = "John"
    Age = 30
    City = "New York"
}
$hashTable.Name  # 访问值

# 字符串操作符
"Hello" + " World"  # 连接
"PowerShell" -replace "Power", "Super"  # 替换
"PowerShell" -contains "Shell"  # 包含
"PowerShell" -like "*Shell"  # 通配符匹配

# 比较操作符
1 -eq 1  # 等于
1 -ne 2  # 不等于
1 -gt 0  # 大于
1 -lt 2  # 小于
1 -ge 1  # 大于等于
1 -le 2  # 小于等于

# 逻辑操作符
$a -and $b  # 逻辑与
$a -or $b   # 逻辑或
-not $a     # 逻辑非

# 赋值操作符
$a = 1      # 赋值
$a += 1     # 加赋值
$a -= 1     # 减赋值
$a *= 2     # 乘赋值
$a /= 2     # 除赋值
```

## 高级功能

```powershell
# 并行处理
$files = Get-ChildItem -Path C:\Logs -Recurse -File
$files | ForEach-Object -Parallel {
    # 并行处理每个文件
    $content = Get-Content $_
    $lineCount = $content.Count
    [PSCustomObject]@{
        FileName = $_.FullName
        LineCount = $lineCount
    }
} -ThrottleLimit 5  # 限制并行任务数

# 工作流
workflow Get-MultiComputerInfo {
    param([string[]]$ComputerName)
    
    foreach -pCHANGE_ME ($computer in $ComputerName) {
        InlineScript {
            $os = Get-CimInstance Win32_OperatingSystem -ComputerName $using:computer
            [PSCustomObject]@{
                ComputerName = $using:computer
                OS = $os.Caption
                Build = $os.BuildNumber
            }
        }
    }
}

# 模块管理
Get-Module -ListAvailable
Import-Module ActiveDirectory
Get-Module
Remove-Module ActiveDirectory
Install-Module PSWindowsUpdate -Force  # 安装模块

# 调试
Set-PSDebug -Trace 1  # 启用脚本调试
Set-PSDebug -Off      # 关闭调试

# 事务
Start-Transaction
New-Item -Path C:\test1.txt -ItemType File -UseTransaction
New-Item -Path C:\test2.txt -ItemType File -UseTransaction
Complete-Transaction  # 提交事务
# 或
# Undo-Transaction  # 回滚事务
```

## 示例脚本

### 1. 系统信息收集脚本

```powershell
# system_info.ps1
function Get-FullSystemInfo {
    param(
        [string]$ComputerName = $env:COMPUTERNAME,
        [string]$OutputFile = "system_info_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv"
    )
    
    try {
        # 获取系统信息
        $systemInfo = @{
            ComputerName = $ComputerName
            Date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            OS = (Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).Caption
            OSVersion = (Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).Version
            BuildNumber = (Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).BuildNumber
            LastBootUpTime = (Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).LastBootUpTime
            Manufacturer = (Get-CimInstance Win32_ComputerSystem -ComputerName $ComputerName).Manufacturer
            Model = (Get-CimInstance Win32_ComputerSystem -ComputerName $ComputerName).Model
            CPU = (Get-CimInstance Win32_Processor -ComputerName $ComputerName).Name
            CPUCores = (Get-CimInstance Win32_Processor -ComputerName $ComputerName).NumberOfCores
            CPUThreads = (Get-CimInstance Win32_Processor -ComputerName $ComputerName).NumberOfLogicalProcessors
            TotalMemoryGB = [math]::Round(((Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName | Measure-Object -Property Capacity -Sum).Sum) / 1GB, 2)
            FreeMemoryGB = [math]::Round(((Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).FreePhysicalMemory * 1KB) / 1GB, 2)
        }
        
        # 获取磁盘信息
        $disks = Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName -Filter "DriveType=3"
        foreach ($disk in $disks) {
            $diskLetter = $disk.DeviceID
            $systemInfo["${diskLetter}_SizeGB"] = [math]::Round($disk.Size / 1GB, 2)
            $systemInfo["${diskLetter}_FreeGB"] = [math]::Round($disk.FreeSpace / 1GB, 2)
            $systemInfo["${diskLetter}_UsedPercent"] = [math]::Round((($disk.Size - $disk.FreeSpace) / $disk.Size) * 100, 2)
        }
        
        # 获取网络适配器信息
        $networkAdapters = Get-NetAdapter -ComputerName $ComputerName -Physical | Where-Object Status -eq 'Up'
        $networkInfo = @()
        foreach ($adapter in $networkAdapters) {
            $ipConfig = Get-NetIPAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4
            $networkInfo += [PSCustomObject]@{
                InterfaceName = $adapter.Name
                MACAddress = $adapter.MacAddress
                IPAddress = $ipConfig.IPAddress
                SubnetMask = $ipConfig.PrefixLength
                DefaultGateway = (Get-NetRoute -InterfaceIndex $adapter.ifIndex -DestinationPrefix '0.0.0.0/0').NextHop
            }
        }
        $systemInfo['NetworkAdapters'] = $networkInfo
        
        # 输出到CSV
        [PSCustomObject]$systemInfo | Export-Csv -Path $OutputFile -NoTypeInformation -Encoding UTF8
        
        Write-Host "系统信息已导出到: $OutputFile"
        return [PSCustomObject]$systemInfo
    }
    catch {
        Write-Error "收集系统信息时出错: $_"
        return $null
    }
}

# 执行脚本
Get-FullSystemInfo
```

### 2. 进程监控和自动终止脚本

```powershell
# monitor_process.ps1
function Monitor-Process {
    param(
        [Parameter(Mandatory=$true)]
        [string]$ProcessName,
        
        [Parameter(Mandatory=$true)]
        [int]$MaxCPU,
        
        [Parameter(Mandatory=$true)]
        [int]$MaxMemoryMB,
        
        [int]$CheckInterval = 60  # 检查间隔（秒）
    )
    
    Write-Host "开始监控进程: $ProcessName"
    Write-Host "CPU阈值: ${MaxCPU}%"
    Write-Host "内存阈值: ${MaxMemoryMB}MB"
    Write-Host "检查间隔: ${CheckInterval}秒"
    Write-Host "按Ctrl+C停止监控..."
    
    try {
        while ($true) {
            $processes = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue
            
            if ($processes) {
                foreach ($process in $processes) {
                    $cpuUsage = $process.CPU
                    $memoryUsageMB = [math]::Round(($process.WorkingSet64 / 1MB), 2)
                    $processInfo = "进程: $($process.Name) (PID: $($process.Id)) - CPU: ${cpuUsage}% - 内存: ${memoryUsageMB}MB"
                    
                    Write-Host $processInfo
                    
                    # 检查是否超过阈值
                    if ($cpuUsage -gt $MaxCPU -or $memoryUsageMB -gt $MaxMemoryMB) {
                        Write-Warning "$processInfo 超过阈值，正在终止..."
                        Stop-Process -Id $process.Id -Force
                        
                        # 记录事件
                        $eventMessage = "自动终止进程: $($process.Name) (PID: $($process.Id)) - CPU: ${cpuUsage}% - 内存: ${memoryUsageMB}MB"
                        Write-EventLog -LogName Application -Source "ProcessMonitor" -EventId 1000 -EntryType Warning -Message $eventMessage -ErrorAction SilentlyContinue
                    }
                }
            } else {
                Write-Host "未找到进程: $ProcessName"
            }
            
            Start-Sleep -Seconds $CheckInterval
        }
    }
    catch {
        Write-Error "监控过程中出错: $_"
    }
}

# 示例用法
# Monitor-Process -ProcessName chrome -MaxCPU 90 -MaxMemoryMB 1000 -CheckInterval 30
```

### 3. 批量文件重命名和组织脚本

```powershell
# organize_files.ps1
function Organize-FilesByDate {
    param(
        [Parameter(Mandatory=$true)]
        [string]$SourcePath,
        
        [string]$DestinationPath = "$SourcePath\Organized",
        
        [ValidateSet("Year", "Month", "Day")]
        [string]$OrganizeBy = "Year"
    )
    
    # 创建目标目录
    if (-not (Test-Path $DestinationPath)) {
        New-Item -Path $DestinationPath -ItemType Directory | Out-Null
        Write-Host "创建目标目录: $DestinationPath"
    }
    
    # 获取所有文件
    $files = Get-ChildItem -Path $SourcePath -File -Recurse
    $totalFiles = $files.Count
    $currentFile = 0
    
    Write-Host "找到 $totalFiles 个文件，开始组织..."
    
    foreach ($file in $files) {
        $currentFile++
        Write-Progress -Activity "组织文件" -Status "正在处理 $currentFile/$totalFiles: $($file.Name)" -PercentComplete (($currentFile / $totalFiles) * 100)
        
        # 获取文件创建日期
        $fileDate = $file.CreationTime
        
        # 根据组织方式创建子目录
        switch ($OrganizeBy) {
            "Year" {
                $subDir = "$DestinationPath\$($fileDate.Year)"
            }
            "Month" {
                $subDir = "$DestinationPath\$($fileDate.Year)\$($fileDate.ToString('yyyy-MM'))"
            }
            "Day" {
                $subDir = "$DestinationPath\$($fileDate.Year)\$($fileDate.ToString('yyyy-MM'))\$($fileDate.ToString('yyyy-MM-dd'))"
            }
        }
        
        # 创建子目录
        if (-not (Test-Path $subDir)) {
            New-Item -Path $subDir -ItemType Directory -Force | Out-Null
        }
        
        # 复制文件到目标位置
        $destinationFile = "$subDir\$($file.Name)"
        
        # 如果文件已存在，添加时间戳
        if (Test-Path $destinationFile) {
            $newFileName = "$($file.BaseName)_$($fileDate.ToString('HHmmss'))$($file.Extension)"
            $destinationFile = "$subDir\$newFileName"
        }
        
        Copy-Item -Path $file.FullName -Destination $destinationFile -Force
    }
    
    Write-Host "文件组织完成！文件已按 $OrganizeBy 组织到: $DestinationPath"
}

# 示例用法
# Organize-FilesByDate -SourcePath "C:\Photos" -OrganizeBy "Month"
```