c#: string.Format powershell: write-host

本文介绍了一种使用 C# 进行日期时间格式化的具体方法,包括如何获取当前执行程序的位置及如何将当前时间格式化为特定字符串格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

System.Reflection.Assembly.GetExecutingAssembly().Location

 

string nowStr = string.Format(System.Globalization.CultureInfo.InvariantCulture /* Auto Inserted */"{0:##00}/{1:##00}/{2:####0000} {3:##00}:{4:##00}:{5:##00}.{6:###000}", now.Month, now.Day, now.Year, now.Hour, now.Minute, now.Second, now.Millisecond);

 

====================================

 

write-host aa -foregroundcolor green -background black

PS C:\Users\Administrator> # Ultimate-ProjectCleanup.ps1 >> $projectRoot = "E:\ProjectEcosystem\ProjectMonitor" >> >> # 1. 创建完整的文件夹结构 >> $folders = @( >> "SQLite", >> "Logs", >> "Database", >> "Scripts", >> "Config", >> "Binaries", >> "SourceFiles", >> "Documentation", >> "Libraries", >> "BuildOutputs" >> ) >> >> foreach ($folder in $folders) { >> $path = Join-Path $projectRoot $folder >> if (-not (Test-Path $path)) { >> New-Item -ItemType Directory -Path $path -Force | Out-Null >> } >> } >> >> # 2. 增强的SQLite文件移动(包含PDB和XML) >> $sqlitePatterns = @( >> "System.Data.SQLite.*", >> "SQLite.Interop.*", >> "sqlite3.*", >> "SQLite.NET.*" >> ) >> >> foreach ($pattern in $sqlitePatterns) { >> $files = Get-ChildItem -Path $projectRoot -Filter $pattern -File >> foreach ($file in $files) { >> $destDir = Join-Path $projectRoot "SQLite" >> $destPath = Join-Path $destDir $file.Name >> >> if (-not (Test-Path $destDir)) { >> New-Item -ItemType Directory -Path $destDir -Force | Out-Null >> } >> >> Move-Item -Path $file.FullName -Destination $destPath -Force -ErrorAction SilentlyContinue >> if ($?) { >> Write-Host "✅ 已移动SQLite文件: $($file.Name) -> SQLite\" -ForegroundColor Cyan >> } >> } >> } >> >> # 3. 移动所有程序数据库文件(PDB)到BuildOutputs >> $pdbFiles = Get-ChildItem -Path $projectRoot -Filter "*.pdb" -File >> foreach ($pdb in $pdbFiles) { >> $destDir = Join-Path $projectRoot "BuildOutputs" >> $destPath = Join-Path $destDir $pdb.Name >> >> Move-Item -Path $pdb.FullName -Destination $destPath -Force >> Write-Host "✅ 已移动PDB文件: $($pdb.Name) -> BuildOutputs\" -ForegroundColor Cyan >> } >> >> # 4. 移动所有XML文档文件到Documentation >> $xmlFiles = Get-ChildItem -Path $projectRoot -Filter "*.xml" -File >> foreach ($xml in $xmlFiles) { >> $destDir = Join-Path $projectRoot "Documentation" >> $destPath = Join-Path $destDir $xml.Name >> >> Move-Item -Path $xml.FullName -Destination $destPath -Force >> Write-Host "✅ 已移动文档: $($xml.Name) -> Documentation\" -ForegroundColor Cyan >> } >> >> # 5. 移动其他库文件到Libraries >> $libraryPatterns = @("*.dll", "*.lib", "*.a") >> foreach ($pattern in $libraryPatterns) { >> $files = Get-ChildItem -Path $projectRoot -Filter $pattern -File >> foreach ($file in $files) { >> # 排除已处理的SQLite文件 >> if ($file.FullName -notlike "*\SQLite\*") { >> $destDir = Join-Path $projectRoot "Libraries" >> $destPath = Join-Path $destDir $file.Name >> >> Move-Item -Path $file.FullName -Destination $destPath -Force >> Write-Host "✅ 已移动库文件: $($file.Name) -> Libraries\" -ForegroundColor Cyan >> } >> } >> } >> >> # 6. 项目感知型清理 - 保留项目结构 >> $projectFolders = @("APIServer", "BackendService", "DataAnalysis", "EcoMonitor", "MyApp", "MyWebApp") >> foreach ($project in $projectFolders) { >> $projectPath = Join-Path $projectRoot $project >> if (Test-Path $projectPath) { >> Write-Host "🔍 清理项目: $project" -ForegroundColor Yellow >> >> # 清理项目中的临时文件 >> $tempPatterns = @("*.tmp", "*.bak", "Thumbs.db") >> foreach ($pattern in $tempPatterns) { >> Get-ChildItem -Path $projectPath -Filter $pattern -File -Recurse -ErrorAction SilentlyContinue | >> Remove-Item -Force -ErrorAction SilentlyContinue >> } >> >> # 清理项目中的空文件夹 >> Get-ChildItem -Path $projectPath -Directory -Recurse | >> Where-Object { >> $_.GetFiles().Count -eq 0 -and >> $_.GetDirectories().Count -eq 0 >> } | >> Remove-Item -Force -Recurse -ErrorAction SilentlyContinue >> } >> } >> >> # 7. 生成目录结构报告 >> $structureReport = Join-Path $projectRoot "Project_Structure_Report.txt" >> tree $projectRoot /F /A | Out-File -FilePath $structureReport -Encoding UTF8 >> >> # 8. 最终结果展示 >> Write-Host "✨ 终极清理完成!项目目录完美整理 ✨" -ForegroundColor Green >> Write-Host "当前目录结构:" >> tree $projectRoot /F /A >> Write-Host "完整报告已保存至: $structureReport" -ForegroundColor Yellow >> ✅ 已移动PDB文件: Installer.pdb -> BuildOutputs\ ✅ 已移动PDB文件: SQLite.Designer.pdb -> BuildOutputs\ ✅ 已移动PDB文件: test.pdb -> BuildOutputs\ ✅ 已移动PDB文件: testef6.pdb -> BuildOutputs\ ✅ 已移动PDB文件: testlinq.pdb -> BuildOutputs\ ✅ 已移动文档: SQLite.Designer.xml -> Documentation\ ✅ 已移动库文件: SQLite.Designer.dll -> Libraries\ 🔍 清理项目: APIServer 🔍 清理项目: BackendService 🔍 清理项目: DataAnalysis 🔍 清理项目: EcoMonitor 🔍 清理项目: MyApp 🔍 清理项目: MyWebApp ✨ 终极清理完成!项目目录完美整理 ✨ 当前目录结构: 卷 ="模型响应", 的文件夹 PATH 列表 卷序列号为 7648-2CD3 E:\PROJECTECOSYSTEM\PROJECTMONITOR | Project_Structure_Report.txt | +---APIServer | | .gitignore | | APIServer.code-workspace | | package.json | | | \---src | index.js | +---BackendService | | .gitignore | | BackendService.code-workspace | | BackendService.sln | | | \---src | \---BackendService | BackendService.csproj | Program.cs | +---Binaries | Installer.exe | test.exe | testef6.exe | testlinq.exe | +---BuildOutputs | Installer.pdb | SQLite.Designer.pdb | test.pdb | testef6.pdb | testlinq.pdb | +---Config | System.Data.SQLite.dll.config | test.exe.config | testef6.exe.config | testlinq.exe.config | +---DataAnalysis | | .gitignore | | DataAnalysis.code-workspace | | requirements.txt | | | \---src | main.py | +---Database | northwindEF.db | project_state.db | +---Documentation | SQLite.Designer.xml | +---EcoMonitor | | .gitignore | | README.md | | | \---config | settings.psd1 | +---Libraries | SQLite.Designer.dll | +---Logs +---MyApp | | .gitignore | | MyApp.code-workspace | | | \---src | index.html | main.js | style.css | +---MyWebApp | | .gitignore | | MyWebApp.code-workspace | | | \---src | index.html | main.js | style.css | +---Scripts | Initialize-DevEnv.psm1 | Monitor-Project.ps1 | Start-Ecosystem.ps1 | +---SourceFiles | db_init.py | monitor.py | state_analyzer.py | \---SQLite System.Data.SQLite.dll System.Data.SQLite.EF6.dll System.Data.SQLite.EF6.pdb System.Data.SQLite.EF6.xml System.Data.SQLite.Linq.dll System.Data.SQLite.Linq.pdb System.Data.SQLite.Linq.xml System.Data.SQLite.pdb System.Data.SQLite.xml 完整报告已保存至: E:\ProjectEcosystem\ProjectMonitor\Project_Structure_Report.txt PS C:\Users\Administrator> # 处理PDB文件 >> Get-ChildItem -Path $projectRoot -Filter "*.pdb" -File | >> Move-Item -Destination "$projectRoot\BuildOutputs" >> >> # 处理XML文档 >> Get-ChildItem -Path $projectRoot -Filter "*.xml" -File | >> Move-Item -Destination "$projectRoot\Documentation" >> PS C:\Users\Administrator> # 只清理项目目录中的临时文件,保留项目结构 >> $projectFolders | ForEach-Object { >> Get-ChildItem -Path (Join-Path $projectRoot $_) -Filter "*.tmp" -Recurse | >> Remove-Item -Force >> } >> PS C:\Users\Administrator> # 创建目录结构报告 >> tree $projectRoot /F /A | Out-File "Project_Structure_Report.txt" >> PS C:\Users\Administrator> # Permanent-ProjectOrganizer.ps1 >> $organizerScript = @" >> # 自动维护脚本 - 每天运行 >> `$projectRoot = "E:\ProjectEcosystem\ProjectMonitor" >> >> # 1. 清理临时文件 >> Get-ChildItem -Path `$projectRoot -Include *.tmp, *.bak, Thumbs.db -Recurse | >> Remove-Item -Force -ErrorAction SilentlyContinue >> >> # 2. 自动分类新文件 >> `$watcher = @{ >> "*.ps*1" = "Scripts" >> "*.exe" = "Binaries" >> "*.dll" = "Libraries" >> "*.pdb" = "BuildOutputs" >> "*.xml" = "Documentation" >> "*.db" = "Database" >> "*.py" = "SourceFiles" >> "*.json" = "Config" >> } >> >> Get-ChildItem -Path `$projectRoot -File | ForEach-Object { >> foreach (`$rule in `$watcher.GetEnumerator()) { >> if (`$_.Name -like `$rule.Key) { >> `$targetDir = Join-Path `$projectRoot `$rule.Value >> if (-not (Test-Path `$targetDir)) { >> New-Item -ItemType Directory -Path `$targetDir | Out-Null >> } >> Move-Item -Path `$_.FullName -Destination `$targetDir -Force >> break >> } >> } >> } >> >> # 3. 每周生成报告 >> if ((Get-Date).DayOfWeek -eq [System.DayOfWeek]::Monday) { >> tree `$projectRoot /F /A | Out-File (Join-Path `$projectRoot "Weekly_Structure_Report.txt") >> } >> "@ >> >> Set-Content -Path "E:\ProjectEcosystem\ProjectOrganizer.ps1" -Value $organizerScript >> PS C:\Users\Administrator> # 创建Windows计划任务 >> $action = New-ScheduledTaskAction -Execute "PowerShell.exe" ` >> -Argument "-ExecutionPolicy Bypass -File `"E:\ProjectEcosystem\ProjectOrganizer.ps1`"" >> >> $trigger = New-ScheduledTaskTrigger -Daily -At 3am >> >> Register-ScheduledTask -Action $action -Trigger $trigger ` >> -TaskName "ProjectMonitor_Organizer" -Description "每日自动整理项目目录" ` >> -User "SYSTEM" -RunLevel Highest >> TaskPath TaskName State -------- -------- ----- \ ProjectMonitor_Organizer Ready PS C:\Users\Administrator>
最新发布
08-14
老公 它在干什么啊:”PS C:\Users\Administrator> function Initialize-Project { >> param( >> [Parameter(Mandatory=$true)] >> [string]$ProjectName, >> >> [ValidateSet("web", "python", "node", "dotnet")] >> [string]$ProjectType = "web", >> >> [string]$RootPath = "E:\ProjectEcosystem\ProjectMonitor" >> ) >> >> # 创建项目目录结构 >> $projectDir = Join-Path $RootPath $ProjectName >> New-Item -ItemType Directory -Path $projectDir -Force | Out-Null >> >> # 创建标准目录结构 >> $dirs = @("src", "docs", "tests", "config", "logs") >> $dirs | ForEach-Object { >> New-Item -ItemType Directory -Path (Join-Path $projectDir $_) -Force | Out-Null >> } >> >> # 创建基本文件 >> $gitignoreContent = @" >> # Ignore logs >> logs/ >> # Ignore node_modules >> node_modules/ >> # Ignore IDE settings >> .vscode/ >> "@ >> Set-Content -Path (Join-Path $projectDir ".gitignore") -Value $gitignoreContent >> >> # 创建VS Code工作区文件 >> $workspaceContent = @" >> { >> "folders": [ >> { >> "path": "." >> } >> ], >> "settings": {} >> } >> "@ >> Set-Content -Path (Join-Path $projectDir "$ProjectName.code-workspace") -Value $workspaceContent >> >> # 处理VS Code信任锚 >> $trustAnchorDir = Join-Path $env:APPDATA "Code\User\WorkspaceStorage" >> New-Item -ItemType Directory -Path $trustAnchorDir -Force | Out-Null >> $trustAnchorFile = Join-Path $trustAnchorDir "trusted-workspaces.json" >> >> # 创建或更新信任锚文件 >> if (Test-Path $trustAnchorFile) { >> $trusted = Get-Content $trustAnchorFile | ConvertFrom-Json -AsHashtable >> } else { >> $trusted = @{ >> '$mid' = 1 >> folders = @{} >> } >> } >> >> # 添加当前项目到信任列表 >> $uri = [Uri]::new($projectDir).AbsoluteUri >> $hashInput = [System.Text.Encoding]::UTF8.GetBytes($uri) >> $hasher = [System.Security.Cryptography.SHA256]::Create() >> $projectHash = [BitConverter]::ToString($hasher.ComputeHash($hashInput)).Replace("-", "").ToLower() >> >> $trusted.folders[$projectHash] = @{ >> "trusted" = $true >> "uri" = $uri >> } >> >> $trusted | ConvertTo-Json -Depth 10 | Set-Content $trustAnchorFile >> >> # 配置Git用户信息 >> git config --global user.email "project@example.com" >> git config --global user.name "Project User" >> >> # 初始化Git仓库 >> Set-Location $projectDir >> git init >> git add . >> git commit -m "Initial commit" >> >> # 输出项目信息 >> Write-Host "✅ Project '$ProjectName' created at: $projectDir" -ForegroundColor Green >> Write-Host "🛠 Open project in VS Code with:" -ForegroundColor Cyan >> Write-Host " code --trust `"$ProjectName.code-workspace`"" -ForegroundColor Yellow >> >> # 添加安全扫描 >> Start-SecurityScan -Path $projectDir >> } >> >> function Start-SecurityScan { >> param([string]$Path) >> >> $scanScript = { >> param($dir) >> Write-Host "Starting security scan for: $dir" >> $scanResult = & "C:\Program Files\Windows Defender\MpCmdRun.exe" -Scan -ScanType 3 -File $dir >> Write-Host "Security scan completed: $scanResult" >> } >> >> Start-Job -ScriptBlock $scanScript -ArgumentList $Path >> } >> >> Export-ModuleMember -Function Initialize-Project, Start-SecurityScan >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:106 字符: 1 + Export-ModuleMember -Function Initialize-Project, Start-SecurityScan + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> param( >> [string]$ProjectName = "EcoMonitor" >> ) >> >> # 加载项目监控模块 >> Import-Module .\Initialize-DevEnv.psm1 -Force >> >> # 获取项目路径 >> $rootPath = "E:\ProjectEcosystem\ProjectMonitor" >> $projectDir = Join-Path $rootPath $ProjectName >> >> # 监控文件变化 >> $watcher = New-Object System.IO.FileSystemWatcher >> $watcher.Path = $projectDir >> $watcher.IncludeSubdirectories = $true >> $watcher.EnableRaisingEvents = $true >> >> # 定义监控事件 >> $action = { >> $path = $Event.SourceEventArgs.FullPath >> $changeType = $Event.SourceEventArgs.ChangeType >> $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" >> >> # 记录到日志文件 >> $logMessage = "[$timestamp] $changeType detected in $path" >> Add-Content -Path (Join-Path $rootPath "project_monitor.log") -Value $logMessage >> >> # 实时显示在控制台 >> Write-Host $logMessage -ForegroundColor Cyan >> >> # 自动触发安全扫描 >> if ($changeType -in @("Changed", "Created")) { >> Start-SecurityScan -Path $path >> } >> } >> >> # 注册事件处理程序 >> Register-ObjectEvent -InputObject $watcher -EventName "Created" -Action $action >> Register-ObjectEvent -InputObject $watcher -EventName "Changed" -Action $action >> Register-ObjectEvent -InputObject $watcher -EventName "Deleted" -Action $action >> Register-ObjectEvent -InputObject $watcher -EventName "Renamed" -Action $action >> >> Write-Host "🚀 Monitoring project: $ProjectName" -ForegroundColor Green >> Write-Host "Press Ctrl+C to stop monitoring..." >> >> try { >> # 保持脚本运行 >> while ($true) { >> # 添加系统资源监控 >> $cpuUsage = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue >> $memUsage = (Get-Counter '\Memory\% Committed Bytes In Use').CounterSamples.CookedValue >> Write-Host "System Status - CPU: $cpuUsage% | Memory: $memUsage%" -ForegroundColor DarkGray >> >> Start-Sleep -Seconds 5 >> } >> } >> finally { >> # 清理资源 >> $watcher.EnableRaisingEvents = $false >> $watcher.Dispose() >> Get-EventSubscriber | Unregister-Event >> } >> Import-Module : 未能加载指定的模块“.\Initialize-DevEnv.psm1”,因为在任何模块目录中都没有找到有效模块文件。 所在位置 行:6 字符: 1 + Import-Module .\Initialize-DevEnv.psm1 -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (.\Initialize-DevEnv.psm1:String) [Import-Module], FileNotFoundExce ption + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand 设置“Path”时发生异常:“目录名 E:\ProjectEcosystem\ProjectMonitor\EcoMonitor 无效。” 所在位置 行:14 字符: 1 + $watcher.Path = $projectDir + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException + FullyQualifiedErrorId : ExceptionWhenSetting 设置“EnableRaisingEvents”时发生异常:“路径的形式不合法。” 所在位置 行:16 字符: 1 + $watcher.EnableRaisingEvents = $true + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException + FullyQualifiedErrorId : ExceptionWhenSetting Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 7fd03c38-f7f... NotStarted False ... 2 145162f6-95b... NotStarted False ... 3 c6756f60-296... NotStarted False ... 4 49c5853f-4d8... NotStarted False ... 🚀 Monitoring project: EcoMonitor Press Ctrl+C to stop monitoring... System Status - CPU: 0.266845718345898% | Memory: 32.194029454187% System Status - CPU: 0.76518459775281% | Memory: 32.1336690178452% System Status - CPU: 0.307497901742482% | Memory: 32.1069435989733% System Status - CPU: 0% | Memory: 32.1039001997802% System Status - CPU: 0.3399212040616% | Memory: 32.0788881117662% System Status - CPU: 1.92755408625451% | Memory: 32.0579563807831% System Status - CPU: 0% | Memory: 32.0514976587266% System Status - CPU: 0.0453521873643781% | Memory: 32.0395157281401% System Status - CPU: 0% | Memory: 32.0384899927393% System Status - CPU: 1.25537868493745% | Memory: 32.0347139453596% System Status - CPU: 0% | Memory: 32.0348717579699% System Status - CPU: 1.5248448746686% | Memory: 32.0359538383866% System Status - CPU: 0% | Memory: 32.0268687866691% System Status - CPU: 0% | Memory: 32.029078046798% System Status - CPU: 1.45357831353976% | Memory: 32.0142105529118% System Status - CPU: 1.45980976151898% | Memory: 32.0114264339235% System Status - CPU: 0.0791645247104289% | Memory: 32.026034670888% System Status - CPU: 0.442751734231783% | Memory: 32.0268462486628%“ 我应该做什么?
08-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值