改进的Get-PSDrive

本文介绍如何使用PowerShell V2内置的Get-PSDrive命令轻松获取磁盘剩余空间,无需编写复杂脚本。文章对比了使用WMI方法与PowerShell V2新特性之间的区别。

平时我们查看剩余空间一定会用WMI写个简单的脚本计算,如下:

这里借用了ToString()方法,这里的“F04”剩余空间数字显示的格式,04是以小数点后四位显示。

 

不过在PowerShell V2里已经不需要自己去写脚本来得到磁盘剩余空间了。因为在V2里与V1相比把Get-PSDrive做了一些改进,如图:

 

$checkpath="C:\healthcheck\"+$(hostname)+"_"+$(Get-Date -Format yyyymmdd) $checkpath if (test-path -path $checkpath){ "Path exist" } else { New-Item -ItemType Directory -Path $checkpath } $(hostname)+" health report about "+$(Get-Date)>> $checkpath\checkrecord.log "`n#check date" >> $checkpath\checkrecord.log Get-Date -Format yyyyddmm >> $checkpath\checkrecord.log "`n#check OS" >> $checkpath\checkrecord.log systeminfo | findstr "OS" >> $checkpath\checkrecord.log "`n#check java" >> $checkpath\checkrecord.log Get-Command java | Select-Object version >> $checkpath\checkrecord.log "`n#check disk" >> $checkpath\checkrecord.log Get-PSDrive | findstr "C:\" >> $checkpath\checkrecord.log "`n#check CPU" >> $checkpath\checkrecord.log Get-WmiObject Win32_Processor |Measure-Object -Property LoadPercentage -Average | select Average >> $checkpath\checkrecord.log "`n#check memory" >> $checkpath\checkrecord.log Get-WmiObject Win32_PhysicalMemory |Measure-Object -Property capacity -Sum | %{$_.sum/1Mb} >> $checkpath\checkrecord.log "`n#check IP" >> $checkpath\checkrecord.log ipconfig >> $checkpath\checkrecord.log "`n#check port opening" >> $checkpath\checkrecord.log netstat -an | findstr 443 >> $checkpath\checkrecord.log netstat -an | findstr 1433 >> $checkpath\checkrecord.log "`n#check service" >> $checkpath\checkrecord.log net start | findstr Apa* >> $checkpath\checkrecord.log net start | findstr SQL* >> $checkpath\checkrecord.log #& "C:\Program Files\Apache Software Foundation\Tomcat 10.1.19\bin\version.bat" > $checkpath\tomcat_ver.log "C:\Users\Administrator\Desktop\apache-tomcat-9.0.90\bin\version.bat" > $checkpath\tomcat_ver.log #$last_log_file=$(Get-Item "C:\Program Files\Apache Software Foundation\Tomcat 9.0.69\logs\catalina*" | Sort-Object LastWriteTime -Descending |Select-Object -Last 1|Select-Object Name) #$last_log_file #Get-ChildItem "C:\Program Files\Apache Software Foundation\Tomcat 9.0.69\logs\" -File|findstr catalina* | Sort-Object LastWriteTime -Descending |Select-Object -Last 1|Select-Object BaseName #Get-Item "C:\Program Files\Apache Software Foundation\Tomcat 9.0.69\logs\catalina*" | Sort-Object LastWriteTime -Descending |Select-Object -Last 1|Select-Object Name #Get-Content -path "C:\Program Files\Apache Software Foundation\Tomcat 9.0.69\logs\catalina..log" -tail 1000 > $checkpath\tomcat.log #[Net.ServicePointManager]::ServerCertificateValidationCallback ={$ture} #Invoke-WebRequest -Uri http://10.56.7.21/bcrf -UseBasicParsing | Select-Object -expand statusCode > $checkpath\checkweb.log Get-Content -path "C:\bcrfLog\logs\debug.log" -tail 1000 > $checkpath\debug.log # check backup log ls "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\" > $checkpath\dbback.log #check db log Get-Content -path "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Log\ERRORLOG" -tail 1000 > $checkpath\db.log 帮我解释这个win server 2019 上的健康检查脚本,并给出改善建议
03-25
PS C:\Users\Administrator> # CurlTools.psm1 >> # ============== >> # 终极修复版模块主文件 >> >> # 初始化模块变量 >> $script:Config = $null >> $script:CurlPath = $null >> $script:ConfigDir = $null >> $script:ConfigPath = $null >> >> # 检测操作系统 - 终极兼容版 >> function Get-Platform { >> try { >> if ($PSVersionTable.PSEdition -eq "Core") { >> if ($IsWindows) { return "Windows" } >> elseif ($IsLinux) { return "Linux" } >> elseif ($IsMacOS) { return "macOS" } >> } else { >> # PowerShell 5.1 兼容处理 >> if ($env:OS -like "Windows*") { >> return "Windows" >> } elseif (Test-Path "/etc/os-release") { >> return "Linux" >> } else { >> return "macOS" >> } >> } >> } catch { >> return "Windows" # 默认返回Windows >> } >> } >> >> # 配置目录获取 - 无环境变量依赖 >> function Get-ConfigDir { >> $platform = Get-Platform >> $tempDir = [System.IO.Path]::GetTempPath() >> >> try { >> switch ($platform) { >> "Linux" { >> $homeDir = [Environment]::GetFolderPath('UserProfile') >> if (-not $homeDir) { $homeDir = "/home/$env:USER" } >> $configDir = "$homeDir/.config/curltools" >> } >> "macOS" { >> $homeDir = [Environment]::GetFolderPath('UserProfile') >> if (-not $homeDir) { $homeDir = "/Users/$env:USER" } >> $configDir = "$homeDir/Library/Application Support/CurlTools" >> } >> default { >> $appData = [Environment]::GetFolderPath('ApplicationData') >> if (-not $appData) { >> $appData = "$env:USERPROFILE\AppData\Roaming" >> } >> $configDir = "$appData\CurlTools" >> } >> } >> } catch { >> $configDir = "$tempDir\CurlTools" >> } >> >> # 确保目录存在 >> if (-not (Test-Path $configDir)) { >> New-Item -ItemType Directory -Path $configDir -Force | Out-Null >> } >> return $configDir >> } >> >> # curl路径检测 - 无依赖终极版 >> function Get-DefaultCurlPath { >> $platform = Get-Platform >> $knownPaths = @{ >> Windows = @( >> "C:\Windows\System32", >> "C:\Program Files\curl\bin", >> "C:\curl\bin", >> "$env:USERPROFILE\curl\bin", >> "C:\Program Files\Git\usr\bin", >> "C:\Program Files\Git\mingw64\bin" >> ) >> Linux = @("/usr/bin", "/usr/local/bin", "/bin", "/snap/bin") >> macOS = @("/usr/local/bin", "/opt/homebrew/bin", "/usr/bin", "/bin") >> } >> >> # 尝试所有已知路径 >> foreach ($path in $knownPaths[$platform]) { >> $curlExe = if ($platform -eq "Windows") { "curl.exe" } else { "curl" } >> $fullPath = Join-Path $path $curlExe >> if (Test-Path $fullPath -PathType Leaf) { >> return $path >> } >> } >> >> # 终极后备方案 - 搜索整个磁盘 >> if ($platform -eq "Windows") { >> $drives = Get-PSDrive -PSProvider FileSystem | Select-Object -ExpandProperty Root >> foreach ($drive in $drives) { >> $curlPath = Get-ChildItem -Path $drive -Filter "curl.exe" -Recurse -ErrorAction SilentlyContinue | >> Select-Object -First 1 -ExpandProperty DirectoryName >> if ($curlPath) { return $curlPath } >> } >> } >> >> return $null >> } >> >> # 模块初始化 - 无依赖实现 >> function Initialize-ModuleConfig { >> try { >> # 获取配置目录 >> $script:ConfigDir = Get-ConfigDir >> $script:ConfigPath = Join-Path -Path $script:ConfigDir -ChildPath "config.json" >> >> # 加载或创建默认配置 >> if (Test-Path $script:ConfigPath) { >> try { >> $script:Config = Get-Content $script:ConfigPath | ConvertFrom-Json >> } catch { >> $script:Config = $null >> } >> } >> >> if (-not $script:Config) { >> $defaultPath = Get-DefaultCurlPath >> >> if (-not $defaultPath) { >> # 终极后备方案 - 下载curl >> $defaultPath = Install-Curl >> } >> >> $script:Config = [PSCustomObject]@{ >> CurlPath = $defaultPath >> LastUpdate = (Get-Date).ToString("o") >> AutoUpdate = $true >> } >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> } >> >> # 设置模块路径 >> $script:CurlPath = $script:Config.CurlPath >> return $true >> } catch { >> return $false >> } >> } >> >> # curl自动安装函数 >> function Install-Curl { >> $platform = Get-Platform >> $tempDir = [System.IO.Path]::GetTempPath() >> >> if ($platform -eq "Windows") { >> $curlZip = "$tempDir\curl.zip" >> $curlUrl = "https://curl.se/windows/dl-8.8.0_5/curl-8.8.0_5-win64-mingw.zip" >> >> # 下载并解压 >> Invoke-WebRequest -Uri $curlUrl -OutFile $curlZip >> Expand-Archive -Path $curlZip -DestinationPath "$tempDir\curl" -Force >> >> # 设置路径 >> $curlPath = "$tempDir\curl\curl-8.8.0_5-win64-mingw\bin" >> return $curlPath >> } else { >> # Linux/macOS 使用包管理器 >> if ($platform -eq "Linux") { >> if (Get-Command apt -ErrorAction SilentlyContinue) { >> sudo apt update >> sudo apt install -y curl >> } elseif (Get-Command yum -ErrorAction SilentlyContinue) { >> sudo yum install -y curl >> } >> } else { >> # macOS >> if (Get-Command brew -ErrorAction SilentlyContinue) { >> brew install curl >> } else { >> /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" >> brew install curl >> } >> } >> >> # 获取安装路径 >> return (Get-Command curl).Source | Split-Path >> } >> } >> >> # 在模块导入时自动初始化配置 >> $initSuccess = Initialize-ModuleConfig >> >> if (-not $initSuccess) { >> # 终极后备方案 - 使用临时curl >> $tempCurl = Install-Curl >> if ($tempCurl) { >> $script:CurlPath = $tempCurl >> Write-Warning "使用临时curl路径: $script:CurlPath" >> } else { >> throw "模块初始化失败且无法安装curl" >> } >> } >> >> # 导出关键函数 >> function Get-CurlPath { >> return $script:CurlPath >> } >> >> function Set-CurlPath { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Path >> ) >> $script:CurlPath = $Path >> $env:Path = "$Path;$env:Path" >> Write-Host "手动设置curl路径: $Path" -ForegroundColor Green >> } >> >> # 其他函数保持不变(Get-FileHashFromUrl, Get-CurlVersion等) >> # ... [原有函数代码] ... >> >> # 导出模块成员 >> Export-ModuleMember -Function Get-CurlPath, Set-CurlPath, Get-CurlVersion, Set-CurlVersion, >> Invoke-SecureDownload, Get-FileHashFromUrl, Update-CurlToolsModule >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:220 字符: 1 + Export-ModuleMember -Function Get-CurlPath, Set-CurlPath, Get-CurlVer ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand
08-13
我记得我之前是powershell7 你要不要检验一下? “Windows PowerShell 版权所有(C) Microsoft Corporation。保留所有权利。 安装最新的 PowerShell,了解新功能和改进!https://aka.ms/PSWindows PS C:\Users\Administrator\Desktop> # 更新Test-RepositoryDependency函数 PS C:\Users\Administrator\Desktop> function Test-RepositoryDependency { >> param( >> [string]$PackageName, >> [string]$RepositoryPath = "E:\ai_pip_repository" >> ) >> >> # 加载包索引(兼容PS 5.x) >> $indexFile = Join-Path $RepositoryPath "package_index.json" >> if (-not (Test-Path $indexFile)) { >> Write-Host "ℹ️ 请先运行 Update-RepositoryIndex 创建索引" -ForegroundColor Yellow >> return >> } >> >> # 兼容旧版PowerShell的JSON解析 >> $jsonContent = Get-Content $indexFile -Raw >> $packageIndex = [System.Collections.Hashtable]::new() >> >> try { >> # PowerShell 5.x兼容方案 >> $rawObject = $jsonContent | ConvertFrom-Json >> $rawObject.PSObject.Properties | ForEach-Object { >> $packageIndex[$_.Name] = @($_.Value | ForEach-Object { >> [PSCustomObject]@{ >> FileName = $_.FileName >> Version = $_.Version >> Size = $_.Size >> LastModified = $_.LastModified >> } >> }) >> } >> } >> catch { >> Write-Host "❌ JSON解析失败: $_" -ForegroundColor Red >> return >> } >> >> # 后续代码保持不变... >> } PS C:\Users\Administrator\Desktop> # 更新Initialize-PipRepository函数 PS C:\Users\Administrator\Desktop> function Initialize-PipRepository { >> param( >> [string]$RepositoryPath = "E:\ai_pip_repository" >> ) >> >> # 检测并处理UNC路径 >> if ($RepositoryPath -match '^\\\\') { >> # 映射网络驱动器 >> $driveLetter = Get-NextAvailableDriveLetter >> $null = New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root (Split-Path $RepositoryPath) -Persist >> $RepositoryPath = "${driveLetter}:\" + (Split-Path $RepositoryPath -Leaf) >> } >> >> # 创建仓库目录(带错误处理) >> try { >> if (-not (Test-Path $RepositoryPath)) { >> $null = New-Item -Path $RepositoryPath -ItemType Directory -Force -ErrorAction Stop >> } >> >> # 目录结构创建代码保持不变... >> } >> catch { >> Write-Host "❌ 目录创建失败: $_" -ForegroundColor Red >> return >> } >> >> # 辅助函数:获取可用驱动器号 >> function Get-NextAvailableDriveLetter { >> $used = Get-PSDrive | Where-Object { $_.Name -match '^[A-Z]$' } | Select-Object -ExpandProperty Name >> $all = 65..90 | ForEach-Object { [char]$_ } >> $available = $all | Where-Object { $_ -notin $used } >> return $available[0] >> } >> } PS C:\Users\Administrator\Desktop> # 更新Install-FromRepository函数 PS C:\Users\Administrator\Desktop> function Install-FromRepository { >> param( >> [Parameter(Mandatory=$true)] >> [string]$PackageName, >> [string]$Version = "latest", >> [string]$RepositoryPath = "E:\ai_pip_repository" >> ) >> >> # 添加版本选择逻辑 >> $localPackages = Get-ChildItem -Path (Join-Path $RepositoryPath "downloaded_packages") -Recurse | >> Where-Object { $_.Name -like "*$PackageName*" -and $_.Extension -in @('.whl', '.gz', '.zip') } >> >> if ($localPackages) { >> # 版本选择逻辑 >> $selectedPackage = if ($Version -eq "latest") { >> $localPackages | >> Sort-Object { [regex]::Match($_.Name, '(\d+\.)+\d+').Value } -Descending | >> Select-Object -First 1 >> } else { >> $localPackages | >> Where-Object { $_.Name -match "$PackageName-$Version" } | >> Select-Object -First 1 >> } >> >> if (-not $selectedPackage) { >> Write-Host "⚠️ 仓库中未找到指定版本: $PackageName==$Version" -ForegroundColor Yellow >> # 回退到下载最新版本 >> $Version = "latest" >> $selectedPackage = $localPackages | >> Sort-Object { [regex]::Match($_.Name, '(\d+\.)+\d+').Value } -Descending | >> Select-Object -First 1 >> } >> >> # 安装时指定--no-deps避免自动解决依赖 >> python -m pip install $selectedPackage.FullName --no-deps --no-index --find-links (Join-Path $RepositoryPath "wheels") >> >> # 单独安装依赖 >> $depReport = Test-RepositoryDependency -PackageName $PackageName >> if ($depReport.MissingDependencies.Count -gt 0) { >> Write-Host "� 安装依赖包..." -ForegroundColor Cyan >> $depReport.MissingDependencies | ForEach-Object { >> Install-FromRepository $_ -RepositoryPath $RepositoryPath >> } >> } >> return >> } >> >> # 下载时指定版本 >> $downloadCommand = if ($Version -eq "latest") { >> "python -m pip download $PackageName -d $tempDir" >> } else { >> "python -m pip download ${PackageName}==${Version} -d $tempDir" >> } >> >> # 后续代码保持不变... >> } PS C:\Users\Administrator\Desktop> # 安装仓库管理模块 PS C:\Users\Administrator\Desktop> Install-Module -Name PipRepositoryManager -Force 需要使用 NuGet 提供程序来继续操作 PowerShellGet 需要使用 NuGet 提供程序“2.8.5.201”或更高版本来与基于 NuGet 的存储库交互。必须在“C:\Program Files\PackageManagement\ProviderAssemblies”或“C:\Users\Administrator\AppData\Local\PackageManagement\ProviderAssembli es”中提供 NuGet 提供程序。也可以通过运行 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force' 安装 NuGet 提供程序。是否要让 PowerShellGet 立即安装并导入 NuGet 提供程序? [Y] 是(Y) [N] 否(N) [S] 暂停(S) [?] 帮助 (默认值为“Y”): PackageManagement\Install-Package : 找不到与指定的搜索条件和程序包名称“PipRepositoryManager”匹配的项目。请尝试使用 Ge t-PSRepository 查看所有可用的注册程序包源。 所在位置 C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:1809 字符: 21 + ... $null = PackageManagement\Install-Package @PSBoundParameters + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Ex ception + FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage PS C:\Users\Administrator\Desktop> Import-Module PipRepositoryManager Import-Module : 未能加载指定的模块“PipRepositoryManager”,因为在任何模块目录中都没有找到有效模块文件。 所在位置 行:1 字符: 1 + Import-Module PipRepositoryManager + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (PipRepositoryManager:String) [Import-Module], FileNotFoundExceptio n + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 初始化仓库 PS C:\Users\Administrator\Desktop> Initialize-PipRepo -Path "E:\ai_pip_repository" Initialize-PipRepo : 无法将“Initialize-PipRepo”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写, 如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + Initialize-PipRepo -Path "E:\ai_pip_repository" + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Initialize-PipRepo:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 安装包(自动处理依赖) PS C:\Users\Administrator\Desktop> Install-PackageFromRepo "torch==2.8.0" Install-PackageFromRepo : 无法将“Install-PackageFromRepo”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名 称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + Install-PackageFromRepo "torch==2.8.0" + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Install-PackageFromRepo:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> Y Y : 无法将“Y”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 行:1 字符: 1 + Y + ~ + CategoryInfo : ObjectNotFound: (Y:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> # 导出当前环境状态 PS C:\Users\Administrator\Desktop> python -m pip freeze > requirements.txt WARNING: Ignoring invalid distribution -odelscope (e:\python310\lib\site-packages) PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 生成仓库快照 PS C:\Users\Administrator\Desktop> $repoPath = "E:\ai_pip_repository" PS C:\Users\Administrator\Desktop> Get-ChildItem (Join-Path $repoPath "downloaded_packages") | >> Select-Object Name, @{Name="Version"; Expression={ >> [regex]::Match($_.Name, '(\d+\.)+\d+').Value >> }} | Export-Csv (Join-Path $repoPath "snapshot.csv") PS C:\Users\Administrator\Desktop>”
最新发布
08-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值