Powershell saving as csv file - csv

Good day!
I am trying to get the opened applications that you can see on the taskbar, the computers' IP address and its username. After which, I would save it in a text file with the values separated by commas. Now, I want everything to be saved in the text file but in my set of codes, the results from Get-process are the only ones that are saved on the text file. How can I include the IP address and the username saved together with the results from Get-process on the same text file.
Here is my code:
$savepath = "C:\Users\$([Environment]::UserName)\Desktop\apps\runningapps.txt"
Get-process | where {$_.mainwindowtitle.length -ne 0} | select name, mainwindowtitle| Export-Csv $savepath -notype
Get-WMIObject -class Win32_ComputerSystem | select username| Export-Csv $savepath -append -notype
Get-WmiObject Win32_NetworkAdapterConfiguration |
Where { $_.IPAddress } | # filter the objects where an address actually exists
Select -Expand IPAddress | # retrieve only the property *value*
Where { $_ -notlike "*:*" }|Export-Csv $savepath -append -notype

I think your issue is because the three objects you are exporting have different attributes, you are having the trouble?
If you really want to put it all on one file, then you could
ConvertTo-Csv -notype | Add-Content $savepath

Related

Expand PSobjects to export to csv

How can I convert the PSobjects returned by Get-Help to strings and export to csv?. I think this is an easy one, but I can't quite get the format I'm looking for. From reading previous answers, I was trying:
Get-Help Get-Content | Select-Object -First 1 -Property #{
Name="temp"
Expression = { $_.Name,$_.Synopsis,$_.syntax,$_.Description }
} | Select-Object -ExpandProperty temp
Which is almost what I want, except it looks like the fields are arrays not strings. I am trying to have just one string for each element, ie (Name, Synopsis, Syntax, etc).
If I try to export that to csv, I get the lengths of the objects instead of the objects themselves:
Get-Help Get-Content | Select-Object -First 1 -Property #{
Name="temp"
Expression = { $_.Name,$_.Synopsis,$_.syntax,$_.Description }
} | Select-Object -ExpandProperty temp | export-csv -NoType -Path $env:HOME\test.txt
I suppose you want to export each property in a seperate column (your script currently only exports one). To do this, you have to select each property. For Syntax and Description I used the Out-String cmdlet to convert it to a string and removed all \r\n to get a valid CSV:
Get-Help Get-Content | Select-Object -First 1 |
Select-Object Name, Synopsis,
#{l='Syntax'; e={($_.Syntax | out-string) -replace "`r?`n"}},
#{l='Description '; e={($_.Description | out-string)-replace "`r?`n"}} |
Export-Csv -Path $env:HOME\test.txt -NoTypeInformation

Using PowerShell to list Object Description

I have a CSV file with a list of PC's in my domain. I wanted to get the "Description" Field information from AD for each of the machines listed in AD. This is what I have so far:
Import-Module ActiveDirectory
Get-ADComputer -Filter {OperatingSystem -NotLike "*Server*"} -SearchBase "OU=Active,OU=Regular Computers,OU=EPComputers,DC=epenergy,DC=net" -Properties * | Select-Object Name,OperatingSystem,CanonicalName | Export-Csv C:\PCList.csv -NoTypeInformation
I am not sure where I need to add in the get-ADObject and filter out the Description Field or even where to begin on that. Any help would be awesome!
Thank You!
You are currently only outputting the following properties: Name,OperatingSystem,CanonicalName to your CVS. If you add Description to the list of objects your are selecting you should also get the Description properties too.
Select-Object Name,OperatingSystem,CanonicalName,Description
this would make your block of code:
Import-Module ActiveDirectory
Get-ADComputer -Filter {OperatingSystem -NotLike "*Server*"} -SearchBase "OU=Active,OU=Regular Computers,OU=EPComputers,DC=epenergy,DC=net" -Properties * | Select-Object Name,OperatingSystem,CanonicalName,Description | Export-Csv C:\PCList.csv -NoTypeInformation
I did my testing using the following though, it returned the name, Description, OperatingSystem and CanonicalName of all of the machines on my domain:
Import-Module ActiveDirectory
Get-ADComputer -Filter * -Properties * | Select-object name,Description,OperatingSystem,CanonicalName | Export-Csv C:\PCList.csv -NoTypeInformation
You might find this website useful, I can almost always find answers to my powershell questions on ss64

Adding to a CSV

I have the following code that basically gets the servername and adds it to a CSV on a UNC. The problem I am having is that if I run it multiple times it keeps appending the header and adding the 2nd server.
First run this is how the file looks:
ServerName
Server1
Second run this is what happens:
ServerName
Server1
ServerName
Server2
How can I prevent this so that the server just gets appended instead of the header being written each time?
This is how my code looks:
$servername = $env:computername
# convert string to an object, otherwise if you output to a CSV it will save the
# strings length instead of the servername
# This entry is for testing
#$servername = "test1"
$obj_list = $servername | Select-Object #{Name='ServerName';Expression={$_}}
# converts to an object and sets no header for the column
#$obj_list | ConvertTo-Csv -NoTypeInformation | % {$_.Replace('"','')} | select -Skip 1 | Add-Content \\test\d$\citrixservers\test1.csv
$obj_list | ConvertTo-Csv -NoTypeInformation | % {$_.Replace('"','')} | Add-Content \\test\d$\citrixservers\servers.csv
Skip the header if the file already exists:
$csv = '\\test\d$\citrixservers\servers.csv'
$skip = if (Test-Path -LiteralPath $csv) { 1 } else { 0 }
$obj_list | ConvertTo-Csv -NoType |
Select-Object -Skip $skip |
ForEach-Object { $_.Replace('"','') } |
Add-Content \\test\d$\citrixservers\test1.csv
You need to use Export-CSV with the -Append parameter rather than ConvertTo-Csv. Here's one way to do it.
$servers = #('server1','server2')
foreach ($server in $servers) {
[pscustomobject]#{'ServerName' = $server} | Export-Csv -Append -Path C:\Servers.csv
}

Grab SamAccountName from SIP attribute with Powershell

I am attempting to grab a SAMAccountName from a SIP address attribute in AD. I keep getting a syntax error that I just can't figure out. I have used similar code to grab a SAMAccountName using the employeeNumber attribute. I have to wonder if the "-" in the attribute name has anything to do with the syntax error.
Import-Csv -Path .\SIP.csv | ForEach-Object {
$sipGet = Get-ADUser -Filter "msRTCSIP-PrimaryUserAddress -eq $($_.'msRTCSIP-PrimaryUserAddress')" |
select -Expand SamAccountName
$_ | select *,#{Name='SamAccountName';Expression={$sipGet}}
} | Export-Csv -Path .\SIP.csv -NoTypeInformation
Any help would be greatly appreciated!
Get-ADUser does not know -eq as a filter. Instead, use plain equal sign, and wrap the string in escaped double quotes.
$sipGet = Get-ADUser -Filter "msRTCSIP-PrimaryUserAddress = \"$($_.'msRTCSIP-PrimaryUserAddress')\"" |
select -Expand SamAccountName
Should do. (Can't test right now, have no access to AD environment)

Creating a Csv using Powershell

I am trying to take a filename such as: John_Doe_E_DOB_1/1/46_M(This is the gender)_ID_0000000_IMG_FileName_Date-of-File_1/1/15_Doc-page-1 And create a CSV file to open in Excel with column headers for: Last Name, First Name, MI, ID No, File Name, Date of File along with doc type. Here's my code so far:
Get-ChildItem -Path C:\Users\name\desktop\test -Recurse | ForEach-Object {$_ | add-member -name "Owner" -membertype noteproperty -value (get-acl $_.fullname).owner -passthru} | Sort-Object fullname | Select BaseName,Name,Owner | Export-Csv -Force -NoTypeInformation C:\Users\name\desktop\test\thing.csv
All this is doing is dropping that really long file name in at the top, and then adding the ext at the end in another column. Example:
John_Doe_E_DOB_1/1/46_M(This is the gender)_ID_0000000_IMG_FileName_Date-of-File_1/1/15_Doc-page-1 Would be in column 1 and
John_Doe_E_DOB_1/1/46_M(This is the gender)_ID_0000000_IMG_FileName_Date-of-File_1/1/15_Doc-page-1.txt <----- Would be the only difference in column 2
How can I split this up for over a million files, all different lengths, and sizes, and get it to break up into the categories listed above? All help would be greatly appreciated.
I would replace the Select stage of your pipeline with a call to a filter function like this:
filter GenObj {
$parts = $_.FullName.Split('_')
new-object pscustomobject -property #{
Owner = (get-acl $_.fullname).owner
FirstName = $parts[0]
LastName = $parts[1]
MiddleInitial = $parts[2]
# Fill in the rest
}
}
Get-ChildItem -Path C:\Users\name\desktop\test -Recurse |
Sort-Object fullname |
GenObj |
Export-Csv -Force -NoTypeInformation C:\Users\name\desktop\test\thing.csv
This will create a new custom object with all the properties on it that correspond to the parts of the filename you want to extract.
This string splitting approach may not work depending on how you handle names with no middle initial.
Also be aware that if you are processing a million files, the use of Sort-Object will cause every single FileInfo object (one for every file) to get buffered in memory so the sort can be performed. You may likely run out of memory and the command will fail. I would consider removing Sort-Object in this scenario.