Getting data from AD via Powershell - powershell

Can someone help?
I'm trying to get data from AD (via PS) in Excel (CSV), but my script put all objects in 1 columns, not in deafferents.
class GoodFree {
static [object[]] Make ([string]$GroupName){
return (Get-ADGroupMember $GroupName |
ForEach-Object {
[PSCustomObject]#{
lic = '1123'
name = $_.Name
gName = $GroupName
}
})
}
[GoodFree]::Make('LV-DPA') | Out-File C:\Users\Downloads\Users.csv

As Scepticalist mentions in their comment, there's a specific Export-Csv cmdlet for CSV-files.
After the pipe use Export-Csv -Path C:\Users\Downloads\Users.csv
Powershell automatically adds type information to CSV-files so you may want to add the -NoTypeInformation switch to the above command to skip that.
If you wish to manage the file encoding you can use the -Encoding switch to for instance get the file in UTF8.
Powershell uses the Windows-culture to determine the standard delimiter for CSV-files, but you can change that with the -Delimiter switch. Add ';' to use semicolons as delimiters for the file.

Related

Powershell Select Specific Text

Hello and thank you for your time. Here is what I am looking to do. I have several log files that I need to search through. I do this by using Get-ChildItem -Path C:\mylogfiles\*.log | Select-String -Pattern 'MyTextHere' However, now I want to complicate my life and only select text that is between single quotes in the log files.
Here is a sample of my log file:
This is some sample text in my log file. It has a lot of garbage that I don't want to see. However, it has text that I want to find, and if found I would like it to save just the selected text to a CSV file. I want to copy everything that is between single quotes. Here comes the text 'Please copy this text that is between the single quotes'
Any idea how I would go about doing this?
The following combines Select-String with ForEach-Object to extract only the phrases of interest (the parts of the line that matched the regex), wraps them in a [pscustomobject] instance with a .Phrase property and exports the results with Export-Csv:
Select-String -Path C:\mylogfiles\*.log -AllMatches -Pattern "'.*?'" |
ForEach-Object {
foreach ($phrase in $_.Matches.Value) {
[pscustomobject] #{ Phrase = $phrase.Trim("'") }
}
} |
Export-Csv -NoTypeInformation -Encoding utf8 result.csv
Note: If there can only ever be at most one phrase of interest per line, you can omit the -AllMatches switch and replace the ForEach-Object call with the following Select-String call, which uses a calculated property:
# ... |
Select-Object -Property #{ Name='Phrase'; Expression={ $_.Matches.Value.Trim("'") } } |
# ...

Get-MsolDevice RegisteredOwners export to CSV fails

I've written a simple script that is attempting to use the input from a source CSV file containing ObjectID's in a column and then exporting the following information; DisplayName, DeviceTrustType, RegisteredOwners, ApproximateLastLoginTimeStamp using the Get-MsolDevice command.
Here's the code I've got so far:
Connect-MsolService
Connect-AzureAD
Get-AzureADDevice -All $True | Select ObjectID | Export-Csv "C:\temp\Project\IntuneDevices\AllAADObjectIDs.csv" -noType
$allobjects = Import-Csv "C:\temp\Project\IntuneDevices\AllAADObjectIDs.csv"
ForEach ($line in $allobjects)
{
Get-MsolDevice -ObjectID $line.ObjectId | Select DisplayName,DeviceTrustType,RegisteredOwners,ApproximateLastLogonTimestamp| Export-Csv -Path "C:\temp\Project\IntuneDevices\Final.csv" -Append -NoTypeInformation
}
The problem is that when I open Final.csv the entry for RegisteredOwners shows up as System.Collections.Generic.List`1[System.String]
When I simply run the command from the terminal without exporting to a CSV so the oputput is displayed on the screen it looks fine, I see the RegisteredOwner listed in curly brackets like {username#domain.org}.
I've read that is because the output for RegisteredOwners is a list item and not simple text like the rest of the output, but I'm having a heck of time converting it inline.
I've tried things like inserting
Select -Property DisplayName,#{ n='RegisteredOwners'; e={ $_.RegisteredOwners -join ';' } }
But that errors during the run no matter the variations I've tried with it.
Any help with this would be greatly appreciated as I've searched and tried multiple solutions but none are working for me.
TIA
Thanks for pushing me in the right direction Bender, turns out I must have had some sort of syntax error I didn't understand. Here is the final code and it's working as intended.
## Script to collect all AzureAD registered devices, their trust type, and their owner.
## Connect to AzureAD and MSOL
Connect-MsolService
Connect-AzureAD
## Get all devices filtering their ObjectID
Get-AzureADDevice -All $True | Select ObjectID | Export-Csv "C:\temp\Project\IntuneDevices\AllAADObjectIDs.csv" -noType
## Create the variable from the expoted Csv
$allobjects = Import-Csv "C:\temp\Project\IntuneDevices\AllAADObjectIDs.csv"
## Create a new file using Column 1 of allobjects.csv entries to suss the information required for each device
ForEach ($line in $allobjects)
{
Get-MsolDevice -ObjectID $line.ObjectId | Select DisplayName,DeviceTrustType,#{ n='RegisteredOwners'; e={ $_.RegisteredOwners -join ';' } },ApproximateLastLogonTimestamp | Export-Csv -Path "C:\temp\Project\IntuneDevices\Final.csv" -Append -NoTypeInformation
}

Need to add AD location Info in the script

I have a script for retrieving AD site and subnet info from the forest. Need to add the location details also to the script
The script is tested and working fine where it gives site and subnet details.
$configNCDN = (Get-ADRootDSE).ConfigurationNamingContext
$siteContainerDN = ("CN=Sites," + $configNCDN)
$siteObjs = Get-ADObject -SearchBase $siteContainerDN -filter { objectClass -eq "site" } -properties "siteObjectBL", name
foreach ($siteObj in $siteObjs) {
$subnetArray = New-Object -Type string[] -ArgumentList $siteObj.siteObjectBL.Count
$i = 0
foreach ($subnetDN in $siteObj.siteObjectBL) {
$subnetName = $subnetDN.SubString(3, $subnetDN.IndexOf(",CN=Subnets,CN=Sites,") - 3)
$subnetArray[$i] = $subnetName
$i++
}
$siteSubnetObj = New-Object PSCustomObject | Select SiteName, Subnets
$siteSubnetObj.SiteName = $siteObj.Name
$siteSubnetObj.Subnets = $subnetArray
$file = "C:\temp\1.csv"
Out-File $file -encoding ASCII -input $siteSubnetObj -append
}
I expect to pull out AD location details also using the script.
You can shorten this script by using the Get-ADReplicationSite command. I would also consider using Export-Csv since you are outputting objects to file.
Get-ADReplicationSite -Filter * -Properties Subnets,Location |
Select #{n='SiteName';e={$_.Name}},
#{n='Subnets';e={$_.Subnets -replace "^CN=(.*?),CN=Subnets,.*$",'$1'}},Location |
Export-Csv -Path 'C:\temp\1.csv' -encoding ASCII -NoTypeInformation
Export-Csv will create a comma delimited file by default (the delimiter is changeable) with the first line (headers) being the property names of your objects. Each other line will contain comma separated values for each of those properties. The columns for properties and values will line up perfectly.
If you have more than 4 subnets per site, the Out-File method alone without changing anything else will cut off the subnet values. You would need to set $formatenumerationlimit to something higher than 4 or -1 for unlimited or make sure the output is not in table format. It will be much harder to work with this file if you don't use Export-Csv because there will not be a consistent delimiter between item properties and their values.
I can add location details to this if you explain exactly what that is.
I do not know what are you referring to with "Location" so can't help there.
Also, I understand the file output is easier to read that way and is probably consumed by a human as a report but you have to consider Out-file will default to your screen width when redirecting to file so the number of subnets which will be saved will depend on that width (and not on a fixed value such as 4). To enlarge the output width you can use the -width parameter
$Something | out-file $file -width 600
or set the default width:
$PSDefaultParameterValues=#{"Out-File:Width"="600"}
Note that large numbers may have undesired side effects.

Replace One CSV Field With Another Through PowerShell

In PowerShell I'm importing a CSV SAMTemp2 which will have a field called SO. Sometimes SO will be populated with "NW" and in these cases I just want to pull the field called ProdProj from the same line and replace the data in SO with the data in ProdProj then export it the data in that condition.
$RepNW = Import-Csv $SAMTemp2
foreach($d in $data){
If($d.SO -eq "NW"){($d.SO).Replace($d.ProdProj)}}
$RepNW | Export-Csv $SAMTemp -NoTypeInformation
I don't get an error, but this doesn't seem to do anything, either. Can anyone assist me, please?
Update
Per Matt below, I tried:
$RepNW = Import-Csv $SAMTemp2
foreach($d in $RepNW){
If($d.SO -eq "NW"){$d.SO = ($d.SO).Replace($d.ProdProj)}}
$RepNW | Export-Csv $SAMTemp -NoTypeInformation
But I'm not seeing any change. Any assistance is appreciated.
As LotPings pointed out in this line foreach($d in $data){, you haven't defined $data and it seems that you mean it to be foreach($d in $RepNW){
Secondly, rather than using Replace() you can just set one property to be equal to the other.
Last, this probably easiest to do all in the pipeline with ForEach-Object
Import-Csv $SAMTemp2 | ForEach-Object {
If($_.SO -eq "NW"){
$_.SO = $_.ProdProj
}
$_
} | Export-Csv $SAMTemp -NoTypeInformation

Powershell to read CSV header with space

I have a powershell script to parse a CSV file and add a new value to specific header. For Example Input file is a header and i want to replace the value under it. I have added the logic and it works for normal hearder but as this header has a space i am not able to manage it. Can you please help me how can i manage the space
Convert into CSV
Import-CSV $CSV_File | ForEach-Object {
{$_.Input file} = "$machine_path\file"
{$_.Output file} ="$machine_path\Output"
$_ | Export-Csv $machine_path\new.csv -NoTypeInformation
}
If you want to dereference a property with spaces in the name, use quotation marks:
Import-CSV $CSV_File | ForEach-Object {
$_.'Input file' = "$machine_path\file"
$_.'Output file' = "$machine_path\Output"
$_
}| Export-Csv $machine_path\new.csv -NoTypeInformation