gpt4 book ai didi

powershell - Where-Object保留空白行

转载 作者:行者123 更新时间:2023-12-03 01:03:07 25 4
gpt4 key购买 nike

我再次陷入了应该如此简单的事情。我有一个CSV文件,需要在其中进行一些字符串修改并将其导出。数据如下所示:

FullName--------\\server\project\AOI\\server\project\AOI\Folder1\\server\project\AOI\Folder2\\server\project\AOI\Folder3\User

I need to do the following:

  • Remove the "\\server\project" from each line but leave the rest of the line
  • Delete all rows which do not have a Folder (e.g., in the example above, the first row would be deleted but the other three would remain)
  • Delete any row with the word "User" in the path
  • Add a column called T/F with a value of "FALSE" for each record

Here is my initial attempt at this:

Get-Content C:\Folders.csv |
% {$_.replace('\\server\project\','')} |
Where-Object {$_ -match '\\'} |
#Removes User Folders rows from CSV
Where-Object {$_ -notmatch 'User'} |
Out-File C:\Folders-mod.csv

这在一定程度上有效,除了它删除了我的标题行并且我还没有找到使用Get-Content添加列的方法。为此,我必须使用 Import-Csv,这很好,但是不断重新加载同一文件似乎效率低下。所以我尝试使用 Import-Csv而不是 Get-Content重写以上代码:

$Folders = Import-Csv C:\Folders.csv
foreach ($Folder in $Folders) {
$Folder.FullName = $Folder.FullName.Replace('\\server\AOI\', '') |
Where-Object {$_ -match '\\'} |
Where-Object {$_ -notmatch 'User Files'}
}
$Folders | Export-Csv C:\Folders-mod.csv -NoTypeInformation

我还没有添加用于添加新列的编码,但这保留了标题。但是,我最终得到了一堆空行,其中 Where-Object删除了该行,而我发现摆脱它们的唯一方法是通过Get-Content命令运行输出文件。对于应该简单的东西来说,这一切似乎都过于复杂。

那么,我想念什么?

最佳答案

感谢TheMadTechnician指出我做错了什么。这是我的最终脚本(添加了其他列):

$Folders= Import-CSV C:\Folders.csv 
ForEach ($Folder in $Folders)
{
$Folder.FullName = $Folder.FullName.replace('\\server\project\','')
}
$Folders | Where-Object {$_ -match '\\' -and $_ -notmatch 'User'} |
Select-Object *,@{Name='T/F';Expression={'FALSE'}} |
Export-CSV C:\Folders.csv -NoTypeInformation

关于powershell - Where-Object保留空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52997976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com