You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell生成带随机数文件名的文件如何复制到远程路径

解决方案

你代码中已经通过$output变量存储了带随机数后缀的Excel文件完整本地路径,直接复用该变量即可完成复制操作,无需额外查找定位文件,仅需要修改注释的远程复制部分代码即可。

修改后完整可运行代码

# 创建文件存储目录
New-Item -Path 'C:\temp\ServerQuery' -ItemType Directory -Force

# 获取设备名和本地用户账户信息
Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'" |
  Select PSComputername, Name, Status, Disabled, AccountType, Lockout, PasswordRequired, PasswordChangeable, SID | Export-Csv C:\temp\ServerQuery\DeviceandUserAccounts.csv -Encoding UTF8 -NoTypeInformation

# 获取本地组信息
Get-LocalGroup | Select Name, Objectclass, Principalsource, sid| Export-Csv C:\temp\ServerQuery\LocalGroup.csv -Encoding UTF8 -NoTypeInformation

# 将CSV文件转换为多工作表Excel工作簿
$path="C:\temp\ServerQuery" # 目标文件夹
Set-Location $path

$csvs = Get-ChildItem .\* -Include *.csv
$y=$csvs.Count
Write-Host "检测到以下CSV文件: ($y)"
foreach ($csv in $csvs)
{
Write-Host " "$csv.Name
}

# 生成带随机数的文件名避免重复
$Random = Get-Random
$outputfilename = $(get-date -f MM-dd-yyyy) + "_" + $env:USERNAME +"_" + "$Random" + "_Server_Query.xlsx" # 文件名规则:日期_用户名_随机数_服务器查询.xlsx
Write-Host "正在生成文件: $outputfilename"
$excelapp = new-object -comobject Excel.Application
$excelapp.sheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
$sheet=1

foreach ($csv in $csvs)
{
$row=1
$column=1
$worksheet = $xlsx.Worksheets.Item($sheet)
$worksheet.Name = $csv.Name
$file = (Get-Content $csv -Encoding UTF8)
foreach($line in $file)
{
$linecontents=$line -split ',(?!\s*\w+")'
foreach($cell in $linecontents)
{
$worksheet.Cells.Item($row,$column) = $cell
$column++
}
$column=1
$row++
}
$sheet++
}
$output = $path + "\" + $outputfilename
$xlsx.SaveAs($output)
$excelapp.quit()
Set-Location \ # 返回根目录

# 清理临时CSV文件
Remove-Item -path C:\temp\ServerQuery\*.csv* -Force

# 复制文件到远程目录,只需替换下面的远程目录路径即可使用
$remoteDir = '\\filesvr\GLOBAL\你的目标目录' # 替换为实际远程目录路径
$remoteFilePath = Join-Path -Path $remoteDir -ChildPath $outputfilename
Copy-Item -Path $output -Destination $remoteFilePath -Force
Write-Host "文件已复制到: $remoteFilePath"

优化说明(可选)

  • 新增了-Force参数避免目录已存在时报错,导出CSV新增编码参数避免中文乱码
  • 远程路径使用Join-Path拼接,自动适配不同系统的路径分隔符,兼容性更好
  • 直接复用已生成的$output变量,不需要额外扫描目录查找带随机数的文件,执行效率更高也不会找错文件

内容的提问来源于stack exchange,提问作者Jeff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:15:01