简体   繁体   English

创建Powershell脚本以循环浏览excel文件并创建文件夹

[英]Creating Powershell script to loop through excel file and create folders

I'm new to Powerscript and looking at writing a solution to loop through an excel file and create a folder for each row in the file. 我是Powerscript的新手,正在寻找编写解决方案以遍历excel文件并为文件中的每一行创建一个文件夹。

At the moment I have the following: 目前,我有以下内容:

$objExcel = new-object -comobject excel.application 

$objExcel.Visible = $True 

$ExcelFilesLocation = “D:\Users\”

$UserWorkBook = $objExcel.Workbooks.Open($ExcelFilesLocation + “ProjectCodes.xlsx”) 

$UserWorksheet = $UserWorkBook.Worksheets.Item(1)

$intRow = 2

Do {

 $Projectcode = $UserWorksheet.Cells.Item($intRow, 1).Value()

 $pos = $userLogOnEmail.IndexOf(“@”)

           $intRow++

           } While ($UserWorksheet.Cells.Item($intRow,1).Value() -ne $null)

$objExcel.Quit()

$a = Release-Ref($UserWorksheet)

$a = Release-Ref($UserWorkBook) 

$a = Release-Ref($objExcel)

The idea is to loop through the project code column for each row. 想法是循环浏览每一行的项目代码列。 Then create a folder that is named for the project code. 然后创建一个以项目代码命名的文件夹。

To create a new directory, use New-Item 要创建新目录,请使用New-Item

For example, assuming $Projectcode is a string containing a valid path: 例如,假设$Projectcode是包含有效路径的字符串:

New-Item -Path $Projectcode -Type Directory

Having spent painful hours wrangling Excel COM objects with PowerShell, my advice is to give up! 花了很多时间用PowerShell处理Excel COM对象后,我的建议是放弃! Office COM objects are confusing, unwieldy and slow. Office COM对象令人困惑,笨拙且缓慢。

Replace the technology you use to access Excel in PowerShell with something better. 用更好的东西替换您在PowerShell中访问Excel所使用的技术。 For example, this module: https://github.com/dfinke/ImportExcel . 例如,此模块: https : //github.com/dfinke/ImportExcel You can use Install-Module ImportExcel -Scope CurrentUser if you're using PS 5. 如果使用的是PS 5,则可以使用Install-Module ImportExcel -Scope CurrentUser

Apart from being easier to use and much faster it doesn't require Excel to be installed, making your final script more portable. 除了更易于使用和更快之外,它不需要安装Excel,从而使最终脚本更易于移植。

Admitedly, you don't get full Excel functionality with this module but since you seem to be doing no more than reading cells, you should be fine. 诚然,您没有使用此模块获得完整的Excel功能,但是由于您似乎只需要读取单元格,就可以了。

Alternatively, Save your Excel file as CSV and use Import-Csv instead. 或者,将Excel文件另存为CSV,然后改用Import-Csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM