基本上,我有一个包含很多列的CSV文件。假设它看起来像这样:
_username, platform_
username1, platformX1
username2, platformY
username3, platformX2
username4, platformX2
..., ...
我想编写一个遍历文件的脚本,对于每个平台,它都会在不同的文件夹中创建具有特定用户名的文件,所以我应该:
\platformX1\username1.file
\platformY\username2.file
\platformX2\username3.file, username4.file
etc etc...
我知道我应该将foreach和if放在某个地方,但是powershell对我来说是新的,我真的不知道如何启动它。
答案 0 :(得分:0)
这与您要执行的操作类似。
这会在您的目录中创建特定大小的文件
$data = get-content "C:\Data\masteFile.csv"
$drcty = "C:\Data"
foreach($line in $data)
{
$a,$b = $line.Split("{,}")
$parent = $drcty+"\"+$a+"\"
$filename = $parent + $b.TRIM() +".txt"
write-host $filename
New-Item -ItemType directory -Path $parent
fsutil file createnew $filename 2000
}
答案 1 :(得分:0)
这似乎可以满足您的要求。 [咧嘴]
# fake reading in a CSV file
# in real life, use Import-CSV
$InStuff = @'
_UserName, Platform_
username1, platformX1
username2, platformY
username3, platformX2
username4, platformX2
'@ | ConvertFrom-Csv
$DestDir = $env:TEMP
$Extension = 'txt'
foreach ($IS_Item in $InStuff)
{
$TargetPath = Join-Path -Path $DestDir -ChildPath $IS_Item.Platform_
if (-not (Test-Path -LiteralPath $TargetPath))
{
# "$Null = " will supress unwanted output from New-Item
$Null = New-Item -Path $TargetPath -ItemType Directory
}
$FileName = $IS_Item._UserName, $Extension -join '.'
$FullFileName = Join-Path -Path $TargetPath -ChildPath $FileName
if (-not (Test-Path -LiteralPath $FullFileName))
{
# "$Null = " will supress unwanted output from New-Item
$Null = New-Item -Path $FullFileName -ItemType File
}
}
我认为这样做很明显,但是我知道我有时会领先于渥太华。因此,如果有任何疑问,请随时提问... [咧嘴]
答案 2 :(得分:0)
这对我有用。
$ErrorActionPreference = "Stop"
#Path of the CSV file resides
$csvData = Import-Csv -Path "$env:USERPROFILE\Desktop\data.csv"
$DestinationFolder = "C:\Stuffs"
foreach($record in $csvData)
{
$destPlatformFolder = $DestinationFolder + "\" + $record.platform_
if(-not(Test-Path -Path $destPlatformFolder)){
New-Item -Path $destPlatformFolder -ItemType Directory -Force | Out-Null
}
$destinationFile = $destPlatformFolder + "\" + $record._username
New-Item -Path $destinationFile -ItemType File -Force | Out-Null
}