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

PowerShell脚本:将CSV输出至目标主机名对应文件夹问题

Fixing PowerShell CSV Export to Computer-Specific Folders

Hey there! Let's get your script exporting CSVs to the right folders (matching $ComputerName) and set it up for regular batch execution. Here's a step-by-step breakdown:

1. Correctly Build the Target Path

The key issue here is safely constructing the path to your existing computer-specific folder in the current working directory. Avoid manual string concatenation—use Join-Path instead, it handles slashes and edge cases automatically.

Example Working Code

# Replace this with your actual data collection logic (e.g., querying remote host info)
$computerData = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName |
    Select-Object Caption, Version, InstallDate

# Define your CSV filename
$csvName = "system-details.csv"

# Build the full path: Current Directory → $ComputerName Folder → CSV File
$targetFolder = Join-Path -Path (Get-Location).Path -ChildPath $ComputerName
$targetCsvPath = Join-Path -Path $targetFolder -ChildPath $csvName

# Export the data (use -Append if you want to add to existing CSVs over time)
$computerData | Export-Csv -Path $targetCsvPath -NoTypeInformation -Append

Write-Host "Successfully saved data to: $targetCsvPath"

2. Batch Processing Multiple Computers

If you're running this against a list of remote hosts, wrap the logic in a loop to iterate through each computer:

# Load your list of computers (from a text file, for example)
$computerList = Get-Content -Path ".\computers.txt"

foreach ($computer in $computerList) {
    $ComputerName = $computer
    $targetFolder = Join-Path -Path (Get-Location).Path -ChildPath $ComputerName

    # Verify the folder exists (you mentioned folders are already there, but this adds safety)
    if (Test-Path -Path $targetFolder -PathType Container) {
        $csvName = "system-details.csv"
        $targetCsvPath = Join-Path -Path $targetFolder -ChildPath $csvName

        # Insert your data collection command here
        Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName |
            Select-Object Caption, Version, InstallDate |
            Export-Csv -Path $targetCsvPath -NoTypeInformation -Append

        Write-Host "Processed $ComputerName successfully"
    } else {
        Write-Warning "Skipping $ComputerName : Folder not found in current directory!"
    }
}

3. Set Up Regular Scheduled Execution

To replace manual runs, use Windows Task Scheduler:

  • Open Task Scheduler → Create Basic Task
  • Set a trigger (daily, weekly, etc.) based on your needs
  • For the action, choose "Start a program"
    • Program/script: powershell.exe
    • Add arguments: -ExecutionPolicy Bypass -File "C:\Full\Path\To\Your\Script.ps1"
  • Make sure the task runs under an account that has:
    • Access to the target folders
    • Permissions to query remote hosts (if using WMI/WinRM)

4. Troubleshooting Why Your Previous Attempts Failed

If adding $ComputerName didn't work before, check these common issues:

  • Variable misassignment: Did you actually set $ComputerName to a valid remote host name? In batch scenarios, make sure you're iterating through your list correctly.
  • Path errors: Manual path concatenation (e.g., (Get-Location) + "\$ComputerName\file.csv") can break if the current directory path doesn't end with a slash. Join-Path fixes this.
  • Working directory confusion: If your script runs from a different directory than you expect, use Get-Location to confirm the current working directory (vs. $PSScriptRoot which is the script's own directory).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:58:40