delete first row of multiple csv in a folder windows command line - csv

I have multiple csv files in a folder.
I want to delete the first row of each csv in the folder using windows command line.
I am not familiar with windows command line so I will need information regarding how to call the folder within the console.
I do not want to make new files with the "subtracted" row, I just want to replace the original file or overwrite it.

Use Powershell
Get-ChildItem "path\to\your\directory" -Filter *.csv |
Foreach-Object {
$import = Get-Content $_.FullName
$import | Select-Object -Skip 1 | Set-Content $_.FullName
}

Related

Moving files based on CSV values

noobie here.
I have a csv file with two columns, they specify source files paths and destinated paths. I have around 1500+ lines to execute. Is there any way to batch process this via a bat file or anything else?
A line in my CSV looks like this:
Source Path,Dest Path
C:\Users\Nick\Pictures\XXXXXXX.img,C:\Users\Nick\Pictures\Export\XXXXXXX.img
I'd probably not solve this with batch files, but rather with PowerShell. It's possible in batch, but notoriously unreliable, especially around characters you don't expect when starting out.
In PowerShell this could be as simple as
Import-Csv files.csv | ForEach-Object {
Move-Item -LiteralPath $_.'Source Path' -Destination $_.'Dest Path'
}
You might need to create directories as required, perhaps something like this:
Import-Csv files.csv | ForEach-Object {
New-Item -ItemType Directory (Split-Path -Parent $_.'Source Path')
Move-Item -LiteralPath $_.'Source Path' -Destination $_.'Dest Path'
}

PowerShell IntelliSense on parameters [duplicate]

The code below is part of a switch and it's working fine, but the problem is: I need to change my file name to 15... Is it possible to to change it so that when I start it, it waits to select for a file with the tab key? Something like when you write Import-Csv in a PowerShell console and press Tab it shows all possbile paths and files.
$names = Import-Csv 15.csv -Header Givenname,Surname -Delimiter ";"
Write-Host "Rename your csv file to '15' and put it in same folder with this script" -ForegroundColor Cyan
pause
foreach ($Name in $Names) {
$FirstFilter = $Name.Givenname
$SecondFilter = $Name.Surname
Get-ADUser -Filter {GivenName -like $FirstFilter -and Surname -like $SecondFilter} |
select Enabled, SamAccountName, DistinguishedName,
#{n="ou";e={($_.DistinguishedName -split ",*..=")[2]}} |
Export-Csv .\sam.csv -NoTypeInformation -Append
}
So you want Intellisense in your script. Ambitious move. Most people would settle for the file browser dialog box. Anyway, I am going to have to refer you to smarter men than me. I was thinking ValidateSet attribute would serve your purpose but I realized that the traditional param block is not enough. So I looked up DynamicParams and this is what I found. This should work for you.
https://blogs.technet.microsoft.com/pstips/2014/06/09/dynamic-validateset-in-a-dynamic-parameter/
The simplest solution is to make your script accept the target file as an argument, by declaring a parameter:
param(
# Declare a mandatory parameter to which the file path of the CSV
# file to import must be passed as an argument on invocation.
[Parameter(Mandatory)]
[string] $FilePath
)
$names = Import-Csv $FilePath -Header Givenname,Surname -Delimiter ";"
foreach ($Name in $Names) {
$FirstFilter = $Name.Givenname
$SecondFilter = $Name.Surname
Get-ADUser -Filter {GivenName -like $FirstFilter -and Surname -like $SecondFilter} |
select Enabled, SamAccountName, DistinguishedName,
#{n="ou";e={($_.DistinguishedName -split ",*..=")[2]}} |
Export-Csv .\sam.csv -NoTypeInformation -Append
}
If you invoke your script without a file path, you will be prompted for it; let's assume your script is located in the current dir. and its name is someScript.ps1:
./someScript # invocation with no argument prompts for a value for $FilePath
Unfortunately, such an automatic prompt is not user-friendly and offers no tab completion.
However, on the command line PowerShell's tab completion defaults to completing file and directory names in the current location, so that:
./someScript <press tab here>
cycles through all files and directories in the current folder.
You can even type a wildcard expression and tab-complete that, if you don't know the full filename or don't want to type it in full:
./someScript *.csv<press tab here>
This will cycle through all *.csv files in the current dir. only.
If you want to go even further and customize tab completion to only cycle through *.csv files, you can use an [ArgumentCompleter({ ... })] attribute (PSv5+):
param(
[Parameter(Mandatory)]
# Implement custom tab-completion based on only the *.csv files in the current dir.
[ArgumentCompleter({
param($cmd, $param, $wordToComplete)
Get-ChildItem -Name "$wordToComplete*.csv"
})]
[string] $FilePath
)
# ...
Now,
./someScript <tab>
will cycle only through the *.csv files in the current directory, if any.
Caveat: As of PowerShell 7.0, tab-completing an argument for which the ArgumentCompleter script block returns no matches (in this case, with no *.csv files present) unexpectedly falls back to the default file- and directory-name completion - see this GitHub issue.
Similarly,
./someScript 1<tab>
will cycle only through the *.csv files in the current directory whose name starts with 1, if any.
As an alternative to using an attribute as part of a script's / function's definition, you can use the PSv5+ Register-ArgumentCompleter cmdlet to attach tab completions to the parameters of any command, i.e., including preexisting ones.
In PSv4- you have two (cumbersome) options for custom tab completion:
Use a dynamic parameter with a dynamically constructed [ValidateSet()] attribute - see the link in Rohin Sidharth's answer.
Customize the tabexpansion2 (PSv3, PSv4) / tabexpansion (PSv1, PSv2) function, but be sure not to accidentally replace existing functionality.
Below is my example.ps1 file that I use to write 1-off scripts. In your case I think you can get what you want with it. For example (no pun intended) you could call this script by typing
C:\PathToYourScripts\example.ps1 [tab]
where [tab] represents pressing the tab key. Powershell intellisense will kick in and offer autocompletion for file names. If your .csv file is not in the current director you can easily use Powershell intellisense to help you find it
C:\PathToYourScripts\example.ps1 C:\PathToCSvFiles[tab]
and powershell will autocomplete. Would-be-downvoters might notice that powershell autocomplete is definitely NOT a complete file-picker but this seems to fulfill the intent of the asked question. Here's the sample.
<#
.NOTES
this is an example script
.SYNOPSIS
this is an example script
.DESCRIPTION
this is an example script
.Example
this is an example script
.LINK
https://my/_git/GitDrive
#>
[CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact="Low")]
param (
[string] $fileName
)
Begin {
}
Process {
if ($PSCmdlet.ShouldProcess("Simulated execution to process $($fileName): Omit -Whatif to process ")) {
Write-Information -Message "Processing $fileName" -InformationAction Continue
}
}
End {
}
If you want to get autocomplete help for multiple parameters just type in the parameter name(s) and press [tab] after each one. Note that leaving the parameters blank will not break the script but you can either extend this to mark the parameters required or just fail with a helpful message. That seems a bit beyond the original question so I'll stop here.

Can I assign Variables from selected Row using out-gridview -passthru

I'm very new to PowerShell and I'm trying to build on older batch files that I made into PowerShell and add some features.
At the moment I have a CSV file which I've used in the pass as a sort of "environment" file, previously I would do batch jobs against this CSV file.
I have a line
Import-Csv "csvfile" | select-object -property * | out-gridview -passthru
The CSV file is built something like:
Name,location,folder
Test,e,Testsite
Test1,c,windows
test2,c,temp
Basically I want to select one of the grows and click Okay and assign the 3 items to variables.. $foldername,$driveLetter,$destinationDirectory
I've looked high and low and I can't seem to manage it I did find one example on StackOverflow which I shamelessly copied, massaged and got to work ... but that gridview is prebuilt by the OP of that post and doesn't have things like the piping to grid-view.-Passthru has (Filter & scroll bar) but I was able to assign variables using this method but my CSV is pretty huge and I want to be able to have it auto size itself and filter / scroll.
You need to use the -OutPutMode Single option of Out-Gridview to restrict selection to a single item from the gridview.
Import-Csv "csvfile" |
select-object -property * |
out-gridview -OutputMode Single -Title 'Select a row' |
ForEach-Object {
$foldername,$driveLetter,$destinationDirectory = $_.Name,$_.location,$_.folder
}

Refer to .CSV for filenames, then Locate and Delete Files Recursively

I'm trying to write a PowerShell script which refers to a CSV file for a list of banned file names (mostly games) and removes them from my users' home folders. I've got it working in the root or target directory, but cannot seem to make it recursive, so that it drills-down through subfolders, despite trying to utilise the -recurse parameter.
As you'll see, I'm not much of a coder, but am trying to learn and better myself. My PS script looks like this:
cd "C:\Test user"
Import-Csv "C:\Games.csv" | foreach {Remove-Item $_.Game -Verbose -Recurse}
and my CSV file looks like this:
Game,Game1.swf,Game2.swf,Game3.swf
Any advice as to what I am missing in order to make this work recursively would be hugely appreciated. Thank you all in advance for being so generous with your time.
You're misunderstanding the structure of CSVs. Essentially CSV is a way to store tabular data (data organized in rows and columns). Your file would have to have the following structure if you want it to work with the code you posted:
Game
Game1.swf
Game2.swf
Game3.swf
The data you posted is just a comma-separated list of values. To process this string you need something like this:
(Get-Content "C:\Games.csv") -split ',' | Remove-Item -Verbose -Recurse
or perhaps like this (if you want to skip the first element):
(Get-Content "C:\Games.csv") -split ',' |
Select-Object -Skip 1 |
Remove-Item -Verbose -Recurse
Edit: If you need to recursively search a folder tree for files from your CSV and then delete just the files you'd do it like this:
$root = 'C:\root\folder'
$items = (Get-Content "C:\Games.csv") -split ',' | Select-Object -Skip 1
Get-ChildItem $root -Recurse -Force |
Where-Object { $items -contains $_.Name } |
Remove-Item -Verbose

Merge CSV files with filtering

I've started to play around with PowerShell some time ago, in order to filter some logs one of my servers is creating.
The individual log is a CSV in text file, where first line is some info about the process creating it. Headers are on the 2nd line, and the actual things are on the 3rd. There are about 15 properties, but I only need couple of them.
Here is what works for me flawlessly on one file:
Import-csv file.txt | Select-Object -Skip 1 -Property prop1, prop2, prop3, prop4, prop5 | Export-csv result.csv -NoTypeInformation
But, whatever I tried to use for multiple files (let's say, all .txt files in said folder, since the logs are created per day, and grouped in folders), it doesn't work for me, and I suspect it's because of the different first line, which I try to skip the same way, but I then get empty merged CSV file with only prop1 as 1st column
Any help is appreciated, thanks!
If the headers are actually on the second line, not the first, then you should probably do
Get-Content file.txt | Select-Object -Skip 1 | ConvertFrom-Csv | Export-Csv result.csv -NoTypeInformation
Because this strips the first line before it gets parsed as CSV.
If you want to merge multiple files in the same way, you can do that similarly:
Get-ChildItem *.txt | ForEach-Object {
Get-Content $_ | Select-Object -Skip 1 | ConvertFrom-Csv
} | Export-Csv result.csv -NoTypeInformation