【问题标题】:Reading a .CSV file and created directories according to values读取 .CSV 文件并根据值创建目录
【发布时间】:2019-10-23 23:09:05
【问题描述】:

我正在使用 PowerShell 调用存储过程并将输出存储在 CSV 文件中。使用相同的脚本,我打算读取 csv 并使用特定列中的值来创建将文件移动到的目录。但是,我需要帮助来创建初始基本代码。

来自 csv 文件的示例记录:

标题:人员类别子类别日期文件

值:Bob Human Male 20191023 C:\Temp\Bob.jpg

工作流程:

对于 SQL 输出中的每一行;

  • 在输出文件夹中创建一个 Person 子文件夹(如果不存在)
  • 在 Person 子文件夹中创建一个类别文件夹(如果不存在)
  • 在类别子文件夹中创建子类别文件夹(如果不存在)
  • 在子类别子文件夹中创建一个日期文件夹(如果不存在)。 (文档日期为 YYYYMMDD 格式)。
  • 将文档文件从源位置复制到文档日期文件夹。

当前代码:

#Variable Parameters
## Do not add final backslash to directory path
    $FilePath="C:\Temp\Output"

#Date Parameters
    Echo "Getting date & time"
        $GetDate=Get-Date
        $DateStr = $GetDate.ToString("yyyyMMdd")
        $TimeStr = $GetDate.ToString("HHmm")

#SQL Connection & SP Execution
    Echo "Establishing SQL Connection"
        $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
        $SqlConnection.ConnectionString = "Server=MyServer;Database=MyDatabase;Integrated Security=True"
        $SqlCmd = New-Object System.Data.SqlClient.SqlCommand

#Run Stored Procedure
    Echo "Running Stored Procedure"
#Return Row Count Print from SP
    Echo "Row Count:" #This result with be printed via the SP
        $SqlCmd.CommandText = "[SCHEMA].[STOREDPROCEDURE]"
        $SqlCmd.Connection = $SqlConnection
        $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
        $SqlAdapter.SelectCommand = $SqlCmd
        $DataSet = New-Object System.Data.DataSet
        $SqlAdapter.Fill($DataSet)

#Close SQL Connection
    Echo "Closing SQL Connection"
        $SqlConnection.Close()

#Output File
    Echo "Outputting File"
        $DataSet.Tables[0] | Export-CSV -notype "$($FilePath)\$($DateStr)_$($TimeStr)_Export.csv"

#Finished Exporting .csv File
    Echo "File Exported to Output Directory"

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您只需一个 New-Item 调用即可创建整个路径,如下所示:

    $rootPath = 'D:\Persons'
    #import your csv file and loop through the results
    Import-Csv -Path 'D:\persons.csv' | ForEach-Object {
        # create the path to output copy the file to
        # [System.IO.Path]::Combine() can combine 4 childpaths in one go
        $subPath  = [System.IO.Path]::Combine($_.Person, $_.Category, $_.Subcategory, $_.Date)
        $fullPath = Join-Path -Path $rootPath -ChildPath $subPath
    
        if (!(Test-Path -Path $fullPath -PathType Container)) {
            New-Item -Path $fullPath -ItemType Directory | Out-Null
        }
        Copy-Item -Path $_.File -Destination $fullPath -WhatIf
    }
    

    如果您对控制台中显示的结果感到满意,请移除 -WhatIf 开关以实际开始复制文件。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      # Import the CSV File    
      $CSVData = Import-CSV -Path C:\Temp\file.csv
      
      # For each record in the CSV file
      $CSVData | foreach-object {
          # Build the personpath string
          $PersonFolder = "C:\$($_.Person)"
      
          # Test if the path (!NOT) exists
          if (!test-path $PersonFolder){
              # Create the person folder
              new-item -path $PersonFolder -ItemType Directory -Force
          }
      
          # Build the category path string (adding to the person folder path)
          $CategoryPath = "$PersonFolder\$($_.Category)"
      
          # Test if the path (!NOT) exists
          <Code Here>
      
          # Create category folder...
      
          # Create date folder etc. etc. etc. 
      }
      

      希望能给你一些想法。

      【讨论】:

      • 嗨,理查德。谢谢你,这肯定是朝着正确方向迈出的一步。我宁愿在 if, else 语句中这样做。 E.G: '# 测试路径是否存在 if (test-path $PersonFolder) Else # 创建 Person 文件夹 new-item -path $PersonFolder -ItemType Directory -Force}' 如果进入下一个目录会发生什么?
      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2017-04-13
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      相关资源
      最近更新 更多