I am using the code below to get a list of computer names where they were last modified 181 days ago. I have a .csv file with 2 columns (ComputerName, UserName) Is there a way I can match the output from the code below with the computername column in the csv file and show the output/matches?
$Days = (Get-Date).AddDays(-181)
Get-ADComputer -Property Name,lastLogonDate -Filter {lastLogonDate -lt $Days} -Server DomainController -Searchbase "OU=US,DC=contoso,DC=net" | FT Name,lastLogonDate
Change ... | FT Name,lastLogonDate to ... | select Name,lastLogonDate. You can still pipe the result into ft to format it as a table, but separating selection from presentation will make it easier to put in additional filters.
For displaying just the computers that have matches in your CSV you could do the following:
$computers = Import-Csv 'your.csv' | % { $_.ComputerName }
Get-ADComputer -Property Name,lastLogonDate ... | select Name,lastLogonDate |
? { $computers -contains $_.Name } | ft
To include the username from the CSV with the result you could do something like this:
$computers = #{}
Import-Csv 'your.csv' | % { $computers[$_.ComputerName] = $_.UserName }
Get-ADComputer -Property Name,lastLogonDate ... |
? { $computers.Keys -contains $_.Name } |
select Name,lastLogonDate,#{n='Username';e={$computers[$_.Name]}} | ft
Related
I am trying to write a powershell script to check all of the online computers and then make it one neat column Here is the code I have so far...
$computers = get-adcomputer -LDAPFilter "(Name=SDA000*)" | Select-Object -Property Name
$computers1 = get-adcomputer -LDAPFilter "(Name=SDA005*)" | Select-Object -Property Name
$computers2 = get-adcomputer -LDAPFilter "(Name=SDA006*)" | Select-Object -Property Name
$computers3 = get-adcomputer -LDAPFilter "(Name=SDA007*)" | Select-Object -Property Name
$computers4 = ($computers) + ($computers1) + ($computers2) + ($computers3)
[array]$online = #($computers4.Name | % {test-connection -erroraction silentlycontinue -Count 1 $_})
$wIw = $online | Select-Object Address
$wIw
But the output always leaves the top 3 lines with extraneous data I don't want. i.e
Address
-------
SDA0003
SDA0007
SDA000B
SDA000C
SDA0050
SDA0051
SDA0054
SDA0057
SDA005F
SDA0061
SDA006B
SDA006D
SDA0076
I can write it to a text file and then pipe it to select-object -skip 3, but that does not seem to work with a variable.
thanks for any advice.
What you are seeing is the header (e.g. the "Address" property). To output it to the screen without the header, you can use the -HideTableHeaders in a Format-Table command:
...
$wIw = $online | Select-Object Address
$wIw | Format-Table -HideTableHeaders
Ohh yes, that treat is sometimes quit helpful but most of the time it is in the way. Here is how I get rid of it:
$computers = (get-adcomputer -LDAPFilter "(Name=SDA000*)" | Select-Object -Property Name).name
Looks like what you want can be done easier like this:
$wIw = (Get-ADComputer -LDAPFilter "(Name=SDA00*)" |
Where-Object { ($_.Name | Test-Connection -Count 1 -Quiet -ErrorAction SilentlyContinue) }).Name
I'm trying to create a Powershell script that creates a CSV from a specific OU, takes the last created computer (ie computer-200), adds 1 (so computer-201) and renames the computer. I was able to create the CSV but haven't been able to add an increment of 1 to the name.
Here is the script so far:
Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”
$OUpath = 'OU=Computers,OU=Test-Devices,DC=Test,DC=local'
$ExportPath = 'c:\temp\computers_in_ou.csv'
Get-ADComputer -Filter * -SearchBase $OUpath -Properties whenCreated | select-object Name,whenCreated | sort whenCreated | Export-Csv -NoType $ExportPath
$csvdata = Import-Csv 'c:\temp\computers_in_ou.csv'
$csvdata | Select-Object Name -Last 1 | Export-Csv -NoType 'c:\temp\renameWS.csv'
$name = Import-Csv 'c:\temp\renameWS.csv' | Select-Object Name -Last 1
The $name shows output of
Name: Computer-200
How can I take that 200 and add 1?
Thank you!
You can use replacing Regex.Replace with a script block to increment the digits in the computer's name by 1:
For example:
[regex]::Replace('computer-200', '\d+', {
param($s)
[int] $n = $s.Value; (++ $n)
})
# Results in: `computer-201`
If you have access to PowerShell Core, Replacement with a script block was added in PowerShell 6 and later:
'computer-200' -replace '\d+', {
$n = [int] $_.Value; (++ $n)
}
Following above examples, you could do the following to get the latest computer name and increment the digits by 1:
$computers = Get-ADComputer -Filter * -SearchBase $OUpath -Properties whenCreated |
Select-Object Name, whenCreated | Sort-Object whenCreated
[regex]::Replace($computers[-1].Name, '\d+', {
param($s)
[int] $n = $s.Value; (++ $n)
})
It really depends on the exact format/trustworthiness of your CSV data, but here's a non-regex way to accomplish this using your existing code.
$csvdata = Import-Csv 'c:\temp\renameWS.csv'
$split = $csvdata[-1].name.Split('-')
$addOne = [int]$split[1] + 1
$final = $split[0] + '-' + $addOne
You can then take that $final string output and append to your CSV, rename with other cmdlets, etc.
Trying to export 4 objects from Ad to a fixed-width txt file with no header.
I need the following columns to be the width that follows.
Employee ID 10
Work Phone 10
Work Phone Extension 5
Work Email Address 50
User ID 20
The following gives me the best output, but doesn't size the columns the way I need. I have been digging around, and think what I need is a bit beyond what I'm comfortable with.
I'm not sure if i need to export with export-csv and then import that into reformat or if I can do out-file directly.
$DateTime = Get-Date -f "yyyyMMdd"
#// Set CSV file name
$CSVFile = "d:\scripts\workday\int002_"+$DateTime+".txt"
Get-ADGroup -Filter {(name -like "*Group Name*")} `
| Get-ADGroupMember -Recursive | Where { $_.objectClass -eq "user" } `
| Get-ADUser -properties * | where {$_.enabled -eq $true} `
| select employeeid,telephoneNumber,mail,sAMAccountName -unique | FT employeeid,telephoneNumber,mail,sAMAccountName -hidetableheaders -autosize | out-file $CSVFile
Sample Output:
8855 2122445710 xxxry.michalsen#companydomain.com michalsenm
You might need to do it manually...
$result = foreach($user in $users) {
$user.employeeid.PadRight(10),
$user.telephoneNumber.PadRight(10),
$user.mail.PadRight(50),
$user.sAMAccountName.PadRight(20) -join ' '
}
$result | Out-File $CSVFile
A revised version that also works if the property is not a string:
$result = foreach($user in $users) {
'{0,-10}{1,-10}{2,-50}{3,-20}' -f
$user.employeeid,
$user.telephoneNumber,
$user.mail,
$user.sAMAccountName
}
$result | Out-File $CSVFile
I'm using the following command to grab users from an OU and export to csv file:
Get-ADUser -Filter * -SearchBase 'OU=Contoso Users,OU=Contoso,DC=domain,DC=local' -Properties * | Select UserPrincipalName, EmailAddress | Sort UserPrincipalName | Export-CSV $UsersToMigrate -NoTypeInformation -Force
Is there anyway to export to multiple csv files of 10 users per file?
Append to the respective output file in a loop and use a counter and integer division to determine the actual filename.
$i = 0
... | Sort UserPrincipalName | ForEach-Object {
$csv = "C:\path\to\output_$([Math]::Floor([int]$i/[int]10)).csv"
$_ | Export-Csv $csv -NoType -Append
$i++
}
$Users = Get-ADUser -Filter * -SearchBase 'OU=Contoso Users,OU=Contoso,DC=domain,DC=local' -Properties * | Select UserPrincipalName, EmailAddress | Sort UserPrincipalName
$Users | ForEach-Object -Begin {$i = 1} {
$_ | Export-CSV "$UsersToMigrate-$([Math]::Ceiling($i++ / 10)).csv" -NoTypeInformation -Append
}
Explanation
Iterates through the collection of users with ForEach-Object, initialising a counter variable $i as 1 in a Begin block first.
Divides the counter by 10 and rounds up to the nearest integer. Uses this as part of the CSV name and exports to the CSV with the -Append switch (requires PSv3+ I believe).
I run this command and I get all computer hostnames in the names.txt file.
Each hostname in the file is on a separate line, but every hostname is followed with white spaces which cause an issue when I try to read this file. How can I output to this file without getting the white spaces on each line?
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | out-file -filepath C:\temp\names.txt
You have the problem that you don't just have names, you have objects with the property 'name', and you also have the problem that Out-File runs complex objects through some kind of formatting before sending them to the file.
To fix both, expand the name out to just text, and generally use Set-Content instead:
Get-ADComputer -filter * | Select-Object -ExpandProperty Name | Sort-Object | Set-Content C:\temp\names.txt
or in short form
Get-ADComputer -filter * | Select -Expand Name | Sort | sc C:\temp\names.txt
or
(Get-ADComputer -filter *).Name | sort | sc C:\temp\names.txt
expandproperty should get rid of the #()
Get-ADComputer -Filter * | sort Name | Select -expandproperty Name | %{ $_.TrimEnd(" ") } | out-file -filepath C:\temp\names
Untested no AD#home
Piping it through this should work (before piping to the out-file):
EDIT: Piping through % { $_.name } should convert #{name=VALUE} to VALUE:
% { $_ -replace ' +$','' } | % { $_.name }
Like this:
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | % { $_ -replace ' +$','' } | % { $_.name } | out-file -filepath C:\temp\names.txt