I am really new to PowerShell and still learning so I am having a requirement to run some of the commands from dbatools and save the results.
$servers = 'E:\DBA\servers.txt'
$outfile = 'E:\DBA\out.csv'
Get-Content $servers | ForEach-Object {Invoke-Command DbaBackupHistory -SQLServer $_ | ConvertTo-CSV -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append $outFile}
I am unsure if this is the correct way to doit
https://dbatools.io/functions/get-dbabackuphistory/
I modified you script and tested. Worked for me. I added 2 more switches to limit result set. -database and -lastfull. You can check documentation for details.
$outfile = 'c:\out.csv'
Get-Content c:\servers.txt|foreach-object {get-DbaBackupHistory -SqlServer $_
-database dbadatabase -lastfull | ConvertTo-CSV -NoTypeInformation |
Select-Object -Skip 1 | Out-File -Append $outFile}
Related
Good day,
I am looking to output result of a Get-NetTcpConnection into a txt and cvs files simultaneously.
This is how I do it now:
$netstat = Get-NetTCPConnection | Select-Object -Property CreationTime,LocalAddress,LocalPort,RemoteAddress,RemotePort,State
$netstat | Export-Csv -Path C:\temp\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HH.mm).csv -NoTypeInformation
$netstat | FT -AutoSize | Out-File -FilePath C:\temp\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HH.mm).txt
Is there a way to do that as a one liner instead of using a variable?
Something like this:
Get-NetTCPConnection | Select-Object -Property CreationTime,LocalAddress,LocalPort,RemoteAddress,RemotePort,State |
Export-Csv -Path C:\temp\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HH.mm).csv -NoTypeInformation;
$_ | FT -AutoSize | Out-File -FilePath C:\temp\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HH.mm).txt
Thank you!
"Tee-object" is build to pass the data/output straight through the pipeline from one end to other end with out format.
Get-NetTCPConnection | Select-Object -Property CreationTime,LocalAddress,LocalPort,RemoteAddress,RemotePort,State |Tee-Object -FilePath "C:\Users\Narayana\Desktop\Testing Dir\temp2.txt" | Export-Excel -Path "C:\Users\Narayana\Desktop\Testing Dir\temp2.xlsx"
I've tried many attempts to get this done in a one liner like you have requested but, have been fruitless.
However, you can always just make your own function to perform this work and run it as a one liner?
function Get-NetStat{
$netstat = Get-NetTCPConnection | Select-Object -Property CreationTime,LocalAddress,LocalPort,RemoteAddress,RemotePort,State
if ($netstat)
{
$netstat | Export-Csv -Path C:\temp\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HH.mm).csv -NoTypeInformation
$netstat | FT -AutoSize | Out-File -FilePath C:\temp\$env:COMPUTERNAME-$(Get-Date -Format yyyyMMdd-HH.mm).txt
}
else
{
Write-Host $Error
}
}
I have the following code.
$summary = . {
while ($true) {
# Generating huge list of psobject
}
} |
Tee-Object -FilePath 'fname.csv' | # Need to process the input objects before writing to CSV
Group-Object -Property xxx | Select Name,Count
However, I need to process the input objects before writing to fname.csv. Is it possible to Tee the object to two pipelines?
I tried
$summary = . {
while ($true) {
# Generating huge list of psobject
}
} |
For-Each {
$_ | ConvertTo-Csv -NoTypeInformation | Out-File -Append 'file.csv'
$_
} |
Group-Object -Property xxx | Select Name,Count
But the headers are repeated every line in file.csv.
I'm not sure what you want to do. Does this help? The objects from get-process get passed to two different pipelines.
get-process cmd | foreach-object { $_ | measure-object
$_ | export-csv -append whatever.csv }
This should do the work in the question. It doesn't Tee to two pipelines, which may be needed for some use cases, though.
$summary = . {
while ($true) {
# Generating huge list of psobject
}
} |
ForEach {
$_ | Export-Csv -NoTypeInformation -Append 'file.csv'
$_
} |
Group-Object -Property xxx | Select Name,Count
Going after #mklement0 's guidance, does the below make it any simpler,
Get-Process excel | Tee-Object -Variable process | group processname | select name, count
$process | Export-Csv "D:\Op_GetProcessExcel.csv" -NoTypeInformation
Previous suggestion
As #AnsgarWiechers pointed out something like the following should work for you,
Get-Process |
group processname |
select name, count |
ConvertTo-Csv -NoTypeInformation |
Tee-Object "C:\Op_GetProcess.csv"
I have this PowerShell query listed below and I require the headers to be machine, path, filewalkmethod
$fs = Get-FileServer
foreach ($s in $fs) {
foreach ($share in $s.Volumes) {
($s.Servername, $share.Share, $share.FileWalkMethod) -join "," |
Out-File -Append D:\data\splunk\otl_varonis\otl_varonis_monitoring.csv
}
}
Sample output:
nas01e,E$,Windows
Updated Query I'm using:
Import-Module -Name VaronisManagement
Connect-Idu
$fs = Get-FileServer
foreach($s in $fs){
$s.Volumes | Select-Object #{n='ServerName'; e={$s.ServerName}}, Share, FileWalkMethod |
Export-CSV D:\data\splunk\otl_varonis\otl_varonis_monitoring_test.csv
-NoTypeInformation -NoClobber }
Untested but this should work:
foreach($s in $fs){
$s.Volumes | Select-Object #{n='Machine'; e={$s.ServerName}}, Share, FileWalkMethod | Export-CSV D:\data\splunk\otl_varonis\otl_varonis_monitoring.csv -NoTypeInformation -Append
}
Note that the parameter -Append for Export-Csv was introduced with PowerShell v3. To make this compatible with earlier versions you could pipeline the loop:
$fs | ForEach-Object {
$machine = $_.ServerName
$_.Volumes | Select-Object #{n='Machine';e={$machine}}, Share, FileWalkMethod
} | Export-Csv D:\data\splunk\otl_varonis\otl_varonis_monitoring.csv -NoType
This powershell code searches the directory and outputs a list of all the files and how old they are to a log file that is parsed buy a different script. all that is working correctly but i also need to keep track of the number of files it found for that dir and the number of files found globally. Thats what the two foreach-Object statements do. but they are staying at 0.
gci -filter *.avi | Select-Object Name, #{Name="Age"; Expression= { (((Get-Date) - $_.CreationTime).Days) }} | Where {$_.Age -ge $daysToKeep} | Out-File -filepath $logFile -append | Foreach-Object {$fileCountCam1++} | Foreach-Object {$fileCount++}
mjolinor's solution is valid, but there's another way (if you can use v3). You can use Tee-Object to write to the file without a loop.
You can also combine your two variable increments into the same script block in the final foreach-object which will speed things up significantly.
gci -filter *.avi |
Select-Object Name, #{Name="Age"; Expression= { (((Get-Date) - $_.CreationTime).Days) }} |
Where {$_.Age -ge $daysToKeep} | Tee-Object -filepath $logFile -append |
Foreach-Object {$fileCountCam1++;$fileCount++}
Out-File is a termnating cmdlet (it doesn't ouput the object to the pipeline), so everything after it isn't getting any input from the pipeline.
See if this works better:
gci -filter *.avi |
Select-Object Name, #{Name="Age"; Expression= { (((Get-Date) - $_.CreationTime).Days) }} |
Where {$_.Age -ge $daysToKeep} |
Foreach-Object {
$_ | Out-File -filepath $logFile -append
$fileCountCam1++
$fileCount++
}
I am trying to append a CSV file. Here are the lines I am using. I wasn't able to find an append option for export-csv unfortunately. Any ideas would be helpful to get this to work.
Get-ADGroupMember "Domain Admins" | select name, samaccountname | Export-Csv c:\bin\DomainAdmins.csv
$admins = Import-Csv C:\bin\DomainAdmins.csv
foreach ($i in $admins) {Get-ADUser $i.samaccountname -properties * | select name, lastlogondate | Export-Csv c:\bin\dalogon.csv}
The documentation suggests that there is an -append flag. The example given ends with
| export-csv –append –path \\Archive01\Scripts\Scripts.csv
Have you tried that? It works fine for me. I'm on version 3, if that matters.
-Append was introduced with PowerShell v3, it's not available in PowerShell v2 and earlier. You can work around it like this, though:
... |
ConvertTo-Csv -NoTypeInformation |
Select-Object -Skip 1 |
Out-File -Append "c:\bin\dalogon.csv"
I ran into this issue also a few days ago. There are a really two solutions I know in Powershell 2. The first would be to save all the data in an array and then use the export-csv commandlet. That did not work for me unless I rewrote my script. I needed to create a CSV and append line by line to build the file. So, I solved it with out-file -append and changing the encoding to ascii.
I basically created a string with my data in it and then piped it to out-file. Here is an example:
$myCSV = "C:\_PSScripts\data\myCSV.csv"
$firstOutputLine = "Column-1,Column-3,Column-3"
$firstOutputLine | out-file $myCSV -Encoding ascii -Force -Append
It's good! but it's only 1 column in CSV file! how to put to many columns as the code below:
Import-Module -Name 'C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ArsPowerShellSnapIn.dll'
$group="HO-Internet","Internet1","Internet2","Internet3"
$group |ForEach-Object {Echo "--------------------Group Name $_ ----------------"; Get-QADGroupMember $_ | Select-Object Email,LogonName,ParentContainer,LastLogon,AccountIsDisabled |ConvertTo-Csv -NoTypeInformation `
| select -Skip 1 `
| Out-File -Append "D:\test.csv"}