Powershell+Export-Excel module - excel

I use Export-Excel module for Powershell. I try to get results of "foreach" from 2 links in a table. But finally i have only one link in the table(only second one). "Out-File" has "=Append",that appends to a file. Maybe there is something like this for "Export-Excel"?
[Reflection.Assembly]::LoadFrom("C:\selenium\net40\WebDriver.dll")
$url = Get-Content D:\dww.txt
$ie = New-Object OpenQA.Selenium.PhantomJS.PhantomJSDriver
foreach ($u in $url) {
$ie.Navigate().GoToUrl($u)
$title = $ie.FindElementByXPath("//h1[contains(#class, 'fullstory')]")
$fullstory = $ie.FindElementByClassName("comment")
$tracklist = $ie.FindElementByXPath("//*[contains(#id,'news-id')]")
$links = $ie.FindElementByXPath("//*[contains(#class, 'link')]")
$img = $ie.FindElementsByclassname("stars").findelementbytagname("img").getattribute("src")
$h = Write-Output Стиль,Формат,"Год выпуска",Размер,"Название альбома",Исполнитель,Треклист,Ссылка,Обложка
$data = ($fullstory.text).split("`n") -replace ": ","=" | Where {$_.Trim()} | Out-String | ConvertFrom-StringData | Foreach {[pscustomobject]$_} | Select $h
$data.Ссылка = $links.text
$data.Треклист = $tracklist.text
$data.Обложка = $img
$data | Export-Excel d:\filedark2.xlsx -AutoSize
Write-Host $u " - выгружено"
}
$ie.Quit()

if you're only using export-excel to save to a new excel document, you might try just exporting to csv using -append and converting to excel afterward with this
https://github.com/gangstanthony/PowerShell/blob/master/Save-CSVasExcel.ps1
...
$data | Export-Csv d:\filedark2.csv -Append -NoTypeInformation
...
}
Save-CSVasExcel d:\filedark2.csv
...

Related

Powershell, how obtain a csv by column with a pscustomobject or ordered?

Being a beginner in Powershell, I have a problem that I can't solve. I get the average of different CSV files as a string with the following code:
# recovery of the list of csv files present in the folder "folder_1".
$files=(Get-ChildItem -path "C:\folder_1\" -Recurse -Include *.csv)
#loop to read each file and average the variables "PRESS_CELL" and "PRESS_DELTA
foreach($file in $files){
$varTemp = #((Get-Content $file | ConvertFrom-Csv | Measure-Object "PRESS_CELL","PRESS_DELTA" -Average | Export-Csv -Path "C:\folder_1\Alias.csv" -NoTypeInformation -Append))
Write-Host $varTemp
}
#added an increment to sort the data (averages)
$vartemp2 = Import-CSV "C:\folder_1\Alias.csv" | Select *,LINENUMBER | ForEach-Object -Begin { $Line = 1 } {
$_.LineNumber = $Line++
$_
} | Export-CSV "C:\folder_1\Alias2.csv" -NoTypeInformation
Write-Host $vartemp2
# sort data by "property" and by "LINENUMBER"
$vartemp3 = Import-Csv "C:\folder_1\Alias2.csv"
$vartemp3 | % { $_.LINENUMBER = [int]$_.LINENUMBER }
$vartemp3 | Sort-Object -Property #{ Expression = 'Property'; Ascending = $true }, #{ Expression = 'LINENUMBER'; Ascending = $true } |
Format-Table -Property "Average","Property","LINENUMBER"
# groups the values obtained in a table/customobject and export it to csv by column ?
$fields = [ordered]#{
PRESS_CELL = $vartemp3 | ? property -like *PRESS_CELL* | Select -ExpandProperty Average
PRESS_DELTA = $vartemp3 | ? property -like *PRESS_DELTA* |Select -ExpandProperty Average
}
$fields | export-csv C:\1_ICOS_data\Alias4.csv -Append ##DOESN'T WORK
[result][1]
However, I would like to export the result as a CSV table (1 column per result with PRESS_CELL and PRESS_DELTA as headers. When I use the pipeline :
| export-csv C:\temp\alias.csv -Append
I get a result :
With "ordered"
"System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","False","System.Object","False"
And with pscustomobject :
System.Object[],"System.Object[]"
Add -NoTypeInformation to export-csv command like that
$fields = [ordered]#{
PRESS_CELL = $vartemp3 | ? property -like *PRESS_CELL* | Select -ExpandProperty Average
PRESS_DELTA = $vartemp3 | ? property -like *PRESS_DELTA* |Select -ExpandProperty Average
}
#Or:
$fields = [pscustomobject]#{
PRESS_CELL = $vartemp3 | ? property -like *PRESS_CELL* | Select -ExpandProperty Average
PRESS_DELTA = $vartemp3 | ? property -like *PRESS_DELTA* |Select -ExpandProperty Average }
$fields |export-csv "c:\fields.csv" -Append -NoTypeInformation

Export-CSV only gets the "Length"

when I try to export to a CSV list, I only get all number for "Length"
.Count property until the split point is reached, then split the CSV array to a new file with a new name that will be used from this point on. What might be the issue?
$RootFolder = Get-Content "c:\DRIVERS\myfile.txt"
foreach ($arrayOfPaths in $RootFolder){
$csv = $arrayofPaths -replace '^\\\\[^\\]+\\([^\\]+)\\([^\\]+).*', 'C:\output\Company_name_${1}_${2}.csv'
$csvIndex = 1
$maxRows = 1000000
$rowsLeft = $maxRows
Get-ChildItem $arrayOfPaths -Recurse | Where-Object {$_.mode -match "d"} | ForEach-Object {
#$csv = $_.FullName -replace '^\\\\[^\\]+\\([^\\]+)\\([^\\]+).*', 'C:\output\Company_name_${1}_${2}.csv'# <- construct CSV path here
$path = $_.FullName
$thisCSV = Get-Acl $path | Select-Object -Expand Access |
Select-Object #{n='Path';e={$path}}, IdentityReference, AccessControlType,
FileSystemRights |
ConvertTo-Csv
if ($thisCSV.count -lt $rowsLeft) {
$thisCSV | Export-Csv $csv -append -noType
$rowsLeft -= $thisCSV.count
} else {
$thisCSV[0..($rowsLeft - 1)] | Export-Csv $csv -append -noType
$csvIndex++
$csv = $csv -replace '\.csv$', "$csvIndex.csv"
if ($thisCSV.count -gt $rowsLeft) {
$thisCSV[$rowsLeft..($thisCSV.count - 1)] | Export-Csv $csv -append -noType
}
$rowsLeft = $maxRows - ($thisCSV.count - $rowsLeft)
}
}
}
Export-CSV is built to take PSCustomObjects as input, not lines of text.
$thisCSV = Get-Acl $path | Select-Object -Expand Access |
Select-Object #{n='Path';e={$path}}, IdentityReference, AccessControlType,
FileSystemRights |
ConvertTo-Csv
The output of this line will be something like:
#TYPE Selected.System.Security.AccessControl.FileSystemAccessRule
"Path","IdentityReference","AccessControlType","FileSystemRights"
"c:\test","BUILTIN\Administrators","Allow","FullControl"
At least three lines, an array of string. What properties does an array of string have?
PS C:\> 'a','b' | Get-Member -MemberType Property
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Length Property int Length {get;}
Length. The only property you see in the CSV, because Export-CSV is exporting all the properties, and that's the only property.
Fix: Remove | ConvertTo-CSV from the Get-ACL line, leave your custom objects as custom objects and let the export handle converting them.
(This should also fix the counting, because it's not counting 3+ lines of text while trying to export 1+ line of data every time).

How to read NTFS permissions in a list of shares from a text file

I am trying to get it easier to use on file servers. I would like to import a file called shares.txt. In that shares.txt there are for example lines, e.g. folder name → root folder and share name → subfolder.
\\10.10.15.240\folder name\share name
\\10.10.15.240\folder name\share2 name
\\10.10.15.240\folder name\share3 name
\\10.10.15.240\folder2 name\share name
\\10.10.15.240\folder2 name\share2 name
\\10.10.15.240\folder2 name\share3 name
and so on.
And I would like to create the output to:
Outputs the data to a text file on \\10.10.15.240\output\ using the folder name and share name as part of the file name
\\10.10.15.240\output\Company_name_$folder name_$share name.csv
\\10.10.15.240\output\Company_name_$folder name_$share2 name.csv
\\10.10.15.240\output\Company_name_$folder name_$share3 name.csv
\\10.10.15.240\output\Company_name_$folder2 name_$share name.csv
\\10.10.15.240\output\Company_name_$folder2 name_$share2 name.csv
\\10.10.15.240\output\Company_name_$folder2 name_$share3 name.csv
and continue.
Do you know how to import this in your script? I tried several things but they all comes up with errors.
Script:
I want to write the permissions list to a CSV file instead of writing it directly to Excel.
$ErrorActionPreference = "SilentlyContinue"
$a = New-Object -ComObject Excel.Application
$a.visible = $true
$b = $a.Workbooks.Add()
$intRow = 1
$c = $b.Worksheets.Item(1)
$c.Cells.Item($intRow,1) = "Folder"
$c.Cells.Item($intRow,2) = "Compte/groupe"
$c.Cells.Item($intRow,3) = "Type d'Acces"
$c.Cells.Item($intRow,4) = "Droits"
$d = $c.UsedRange
$d.EntireColumn.AutoFit()|Out-Null
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $true
Remove-Variable arrayOfPath
$depth = 2
$RootFolder = "\\MySRV\Folder"
for ($i=0; $i -le $depth; $i++) {
$arrayOfPath += ,$RootFolder
$RootFolder = $RootFolder + "\*"
}
$arrayOfPath | Get-ChildItem | %{
Get-Acl $_.FullName
} | %{
$intRow = $intRow + 1
$c.Cells.Item($intRow, 1) = $_.Path.ToString().Replace("Microsoft.PowerShell.Core\FileSystem::", "")
$droit = $_.Access
$droit | %{
$c.Cells.Item($intRow, 2) = $_.IdentityReference.ToString();
$c.Cells.Item($intRow, 3) = $_.AccessControlType.ToString();
$c.Cells.Item($intRow, 4) = $_.FileSystemRights.ToString();
$intRow = $intRow+1
}
}
$d.EntireColumn.AutoFit() | Out-Null
Last Update:
$arrayOfPaths= Get-Content "\\UNC PATH\myfile.txt"
Get-ChildItem $arrayOfPaths -Recurse | Where-Object {$_.mode -match "d"} | ForEach-Object {
$csv = $_.FullName -replace '^\\\\[^\\]+\\([^\\]+)\\(.*)', '\\UNC PATH\Company_name_${1}_${2}.csv' # <- construct CSV path here
$path = $_.FullName
Get-Acl $path | Select-Object -Expand Access |
Select-Object #{n='Path';e={$path}}, IdentityReference, AccessControlType,
FileSystemRights |
Export-Csv $csv -Append -NoType
}
Basically you'd do something like this:
loop over the paths
get each folder's ACL
expand the ACEs
select the ACE properties you want exported
add the path with a calculated property
export the selected properties to a CSV
Appending to the output CSV(s) inside the loop allows you to control to which file each ACL is exported. You can for instance make the file name depend on elements of the source path, or the number of elements already written (if you add a counter variable).
Get-ChildItem $arrayOfPaths | ForEach-Object {
$csv = "..." # <- construct CSV path here
$path = $_.FullName
Get-Acl $path | Select-Object -Expand Access |
Select-Object #{n='Path';e={$path}}, IdentityReference, AccessControlType,
FileSystemRights |
Export-Csv $csv -Append -NoType
}
}
Note that -Append was added to Export-Csv in PowerShell v3. On earlier versions you can sort of emulate it with ConvertTo-Csv and Add-Content.

Importing large csv file into Excel using PowerShell

I'm writing a script which imports a large csv file in Excel document.
I try to use a faster way to enter the data and pass the array directly to Excel without looping it.
$p = Import-Csv -Path "C:\Report.csv" -Delimiter "`t"
$Excel01 = New-Object -ComObject Excel.Application
$Excel01.Visible = $True
$Workbook01 = $Excel01.Workbooks.Add()
$Worksheet01 = $Workbook01.Sheets.Item(1)
$Worksheet01.Activate()
$Worksheet01.Range("A1:D1").EntireColumn.Value() = $p | select field1,field2...
But when I run this it hungs...How can I do that?
OpenText() already exists in Excel. Note, however, that you MUST change the extension of the text file to something other than .csv, because Excel has its own mind about how files with that particular extension should be handled.
New-Variable -Option Constant -Name xlDelimited -Value 1
New-Variable -Option Constant -Name xlTextQualifierNone -Value -4142
New-Variable -Option Constant -Name xlWorkbookDefault -Value 51
$csv = 'C:\path\to\your.csv'
$txt = $csv -replace '\.csv$','.txt'
$xls = $csv -replace '\.csv$','.xlsx'
Rename-Item $csv $txt
$xl = New-Object -COM 'Excel.Application'
$xl.Workbooks.OpenText($txt, [Type]::Missing, [Type]::Missing, $xlDelimited, $xlTextQualifierNone, $false, $true)
$wb = $xl.Workbooks | ? { $_.FullName -eq $txt }
$wb.SaveAs($xls, $xlWorkbookDefault)
$wb.Close()
$xl.Quit()
The [Type]::Missing values are required for parameters that should retain their default value.
Quick and dirty. Maybe you can optimize it :-)
$p = Import-Csv -Path "C:\Report.csv" -Delimiter "`t"
$Excel01 = New-Object -ComObject Excel.Application
$Excel01.Visible = $True
$Workbook01 = $Excel01.Workbooks.Add()
$Worksheet01 = $Workbook01.Sheets.Item(1)
$Worksheet01.Activate()
#Add csv header to excel
For ($i = 0; $i -lt ($p | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"}).Count; $i ++) {
$Worksheet01.Cells.Item(1,(1+$i)) = "$(($p | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"})[$i].Name)"
}
#Add csv data to ecxel
$startRow = 2
For ($i = 0; $i -lt ($p | Measure-Object).Count; $i ++) {
For ($i2 = 0; $i2 -lt ($p[$i] | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"}).Count; $i2 ++) {
$PropertyName = ($p[$i2] | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"})[$i2].Name
$Worksheet01.Cells.Item($startRow,(1+$i2)) = "$($p[$i].$PropertyName)"
}
$startRow ++
}

Powershell filter a List by Name and Date

I need a bit of help... I'm new to powershell and i want to Filter a List (csv). I would love to remove all lines with certain names in it. and cut the list down to the last month. In the script you can see how far i got till now.
param(
[Parameter(ValueFromPipeline=$true,HelpMessage="Enter CSV path(s)")]
[String[]]$Path = $null
)
if($Path -eq $null) {
Add-Type -AssemblyName System.Windows.Forms
$Dialog = New-Object System.Windows.Forms.OpenFileDialog
$Dialog.InitialDirectory = "$InitialDirectory"
$Dialog.Title = "Select CSV File(s)"
$Dialog.Filter = "CSV File(s)|*.csv"
$Dialog.Multiselect=$true
$Result = $Dialog.ShowDialog()
if($Result -eq 'OK') {
Try {
$Path = $Dialog.FileNames
}
Catch {
$Path = $null
Break
}
}
else {
Write-Host -ForegroundColor Yellow "Notice: No file(s) selected."
Break
}
}
$info=Import-Csv "$path" -Delimiter ';'
$info | Get-Member
$info | Format-Table
as you can see i tryed to link the path to a filebrowser.
For the purposes of discussion, I will assume that the full pathname of the CSV is in the variable $InputPath, and that you want to write the result to a CSV file whose full pathname is in the variable $OutputPath. I will also assume that the CSV file contains a column named 'Name', and that the value from the Name column that you want to exclude is in the variable $ExcludedName. Given that, you can simply do
Import-CSV -Path $InputPath | Where-Object {$_.Name -ne $ExcludedName} | Export-CSV -Path $OutputPath -NoTypeInformation
You can do this by my code,but dont forget that first row must contains names of column and delimiter must be ';' and $nameslist is array of names that you need delete:
$info=Import-Csv "D:\testdir\file2.csv" -Delimiter ';'
$nameslist=#('James','John','andrew')
foreach($i in $info){
if($nameslist -contains $i.Name){
$i.Name=""
}
$i|Export-Csv -Path "D:\testdir\file1.csv" -Delimiter ';' -NoTypeInformation -Force -Encoding UTF8 -Append
}
Try this:
$data = Import-Csv "Path" | Select-Object * -ExcludeProperty Names
$data | export-csv "Path" -Notype
This will cut the column names.
Try it first without using a function:
Import-Csv <Filename> | Where-Object {$_.<FieldName> -notlike "*<Value>*"}
Also, you might consider something like this:
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true, HelpMessage = "Enter CSV path(s)")]
[String[]]$Path = $(
Add-Type -AssemblyName System.Windows.Forms
$DialogProperties = #{
Title = 'Select CSV File(s)'
Filter = 'CSV File(s)|*.csv'
Multiselect = $True
}
$Dialog = New-Object System.Windows.Forms.OpenFileDialog -Property $DialogProperties
$Dialog.ShowDialog()
If ($Result -eq 'OK') {
$Path = $Dialog.FileNames
} Else {
Write-Error 'Notice: No file(s) selected.'
}
)
)
Process {
ForEach ($PathItem in $Path) {
Import-Csv $PathItem | Where-Object { $_.Name -notlike "*NotThisOne*" }
}
}

Resources