我正在使用PowerShell调用存储过程,并将输出存储在CSV文件中。使用相同的脚本,我打算读取csv并使用特定列中的值来创建目录,然后将文件移入其中。但是,我需要帮助来创建初始基本代码。
标题:人员类别子类别日期文件
值:Bob Human Male 20191023 C:\ Temp \ Bob.jpg
对于SQL输出中的每一行;
当前代码:
#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"
答案 0 :(得分: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
开关以开始实际复制文件。
答案 1 :(得分:0)
您可以执行以下操作:
# 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.
}
希望能给您一些想法。