PowerShell - iterating over computer names in Active Directory - powershell

I'm new to PowerShell and I'm attempting to write a script that will query AD for machine names, check which ones are responding and write the output into a file. So far I have this:
$computers = Get-ADComputer -filter {(Name -like "PC*")} | Select-Object -Property Name
foreach ($computer in $computers) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -Ea 0 -Quiet)) {
"Machine $computer connected." | Out-File "out.txt" -Append
} else {
"Machine $computer not connected." | Out-File "out.txt" -Append
} #end if
} #end foreach
What I get in the output text file looks like the following:
...
Machine #{Name=PC-0649} not connected.
Machine #{Name=PC-1541} not connected.
Machine #{Name=PC-1574} not connected.
...
I think my problem lies with the Select-Object -Property Name part of the first line. Running the debugger, it looks like PowerShell is formatting each iteration of $computer to include the header line.
[DBG]: PS Y:\>> $computer
Name
----
PC-0649
What's the best way for me to strip out everything except the PC-#### part in this situation?

I think your problem is that you still have a list of (truncated) computer objects in $computers. Verify this by doing $computers[0].GetType(). If you don't see String, it's not a string. :) Try this instead:
$computers = Get-ADComputer -filter {(Name -like "PC*")} |
Select-Object -ExpandProperty Name

Related

Powershell - Export CSV file correctly

I hope someone can help me with this. We want to see which computers have a HDD and SDD. I have an excel.csv of the computers. I import the computers. But when I export them I never see the csv or its incomplete. Can you tell what part of my script is incorrect. Thank you
$computers = Import-csv -path "C:\Temp\MediaType\Computers.csv"
foreach ($computer in $computers) {
Write-Host "`nPulling Physical Drive(s) for $computer"
if((Test-Connection -BufferSize 32 -Count 1 -ComputerName $computer -Quiet)){
Invoke-Command -ComputerName $computer -ScriptBlock {
Get-WmiObject -Class MSFT_PhysicalDisk -Namespace root\Microsoft\Windows\Storage | Select-Object sort -Property PSComputerName, Model, SerialNumber, MediaType
Export-Csv C:\Temp\devices.csv
}
}
}
Update: 11/11/2021
Thank you everyone for you help
This script worked for me:
$ExportTo = "C:\Temp\devices.csv"
$computers = Import-csv -path "C:\Temp\Computers.csv"
{} | Select "ComputerName", "Status", "Model", "SerialNumber", "MediaType" | Export-Csv $ExportTo
$data = Import-csv -path $ExportTo
foreach ($computer in $computers) {
$Online = Test-Connection -BufferSize 32 -Count 1 -ComputerName $computer.computer -Quiet
if ($Online) {
Write-Host $computer.computer " is Online"
$OutputMessage = Get-CimInstance -ClassName MSFT_PhysicalDisk -Namespace root\Microsoft\Windows\Storage -ComputerName $computer.computer | Select-Object -Property PSComputerName,#{N='Status';E={'Online'}}, Model, SerialNumber, MediaType
$data.ComputerName = $computer.computer
$data.Status = $OutputMessage.Status
$data.Model = $OutputMessage.Model
$data.SerialNumber = $OutputMessage.SerialNumber
$data.MediaType = $OutputMessage.MediaType
$data | Export-Csv -Path $ExportTo -Append -NoTypeInformation
} else {
Write-Host $computer.computer " is Offline"
$data.ComputerName = $computer.computer
$data.Status = "Offline"
$data.Model = ""
$data.SerialNumber = ""
$data.MediaType = ""
$data | Export-Csv -Path $ExportTo -Append -NoTypeInformation
}
}
Continuing from my comment. . . as is, you would be exporting the results to the remote machine. That's if it was piped properly. You're currently missing a pipe (|) before Export-Csv.
Also, there's no need to invoke the command, as Get-WMIObject has a parameter for remote computers: -ComputerName. It's also a deprecated cmdlet that has been replaced by Get-CimInstance.
$ExportTo = "C:\Temp\devices.csv"
$computers = Import-csv -path "C:\Temp\MediaType\Computers.csv"
foreach ($computer in $computers)
{
Write-Host "`nPulling Physical Drive(s) for $computer"
if (Test-Connection -BufferSize 32 -Count 1 -ComputerName $computer -Quiet) {
Get-CimInstance -ClassName MSFT_PhysicalDisk -Namespace root\Microsoft\Windows\Storage -ComputerName $computer |
Select-Object -Property PSComputerName, Model, SerialNumber, MediaType |
Export-Csv -Path $ExportTo -Append -NoTypeInformation
}
}
Side Note: Get-CimInstance accepts an array of strings, meaning you can pass the entirety of $Computers to it. This should allow it to perform the the query in parallel, vs serial (one at a time):
$ExportTo = "C:\Temp\devices.csv"
$computers = Import-csv -path "C:\Temp\MediaType\Computers.csv"
Get-CimInstance -ClassName MSFT_PhysicalDisk -Namespace root\Microsoft\Windows\Storage -ComputerName $computers -ErrorAction SilentlyContinue |
Select-Object -Property PSComputerName, Model, SerialNumber, MediaType |
Export-Csv -Path $ExportTo -Append -NoTypeInformation
Performing queries one at a time doesn't necessarily mean it's bad. You can actually have more control over the control of flow for your script.
EDIT:
Following up on your comment...you're no longer using your if statement to check if the computer is online before connecting. So given that you keep the if statement, and add an else condition, you can create a calculated property to add another property to export of Status. Then, you can pass it a value of Online, or Offline depending on if the machine is online or not:
$ExportTo = "C:\Temp\devices.csv"
$computers = Import-csv -path "C:\Temp\MediaType\Computers.csv"
foreach ($computer in $computers)
{
if (Test-Connection -BufferSize 32 -Count 1 -ComputerName $computer -Quiet) {
Write-Host -Object "`nPulling Physical Drive(s) for $computer"
Get-CimInstance -ClassName MSFT_PhysicalDisk -Namespace root\Microsoft\Windows\Storage -ComputerName $computer |
Select-Object -Property PSComputerName,#{N='Status';E={'Online'}}, Model, SerialNumber, MediaType |
Export-Csv -Path $ExportTo -Append -NoTypeInformation -Force
}
else {
Write-Host -Object "`n$Computer is Offline"
[PSCustomObject]#{PSComputerName=$Computer;Status='Offline'} | Export-Csv -Path $ExportTo -Append -Force
}
}
Also:
Always remember that even if you can ping a machine, it doesn't mean you can connect to it.
This can be mitigated by using a CIM Session, or PSSession depending on the type of commands you're running.
To specifically answer the question:
How do I correctly export a CSV file (use Export-Csv)?
You might want to read about PowerShell pipelines and PowerShell cmdlets.
Basically, a cmdlet is a single command that participates in the pipeline semantics of PowerShell. A well written cmdlet is implemented for the Middle of a Pipeline which means that it processes ("streams") each individual item received from the previous cmdlet and passes it immediately to the next cmdlet (similar to how items are processed in an assembly line where you can compare each assembly station as a cmdlet).
To better show this, I have created an easier minimal, complete and verifiable example (MVCE) and replaced your remote command (Invoke-Command ...) which just an fake [pscustomobject]#{ ... } object.
With that;
I have used Get-Content rather then Import-Csv as your example suggest that Computers.csv is actually a text file which list of computers and not a Csv file which would require a (e.g. Name) header and using this property accordingly (like $Computer.Name).
To enforce the pipeline advantage/understanding, I am also using the ForEach-Object cmdlet rather than the foreach statement which is usually considered faster but this is probably not the case here as for the foreach statement it is required to preload all $Computers into memory where a well written pipeline will immediately start processing each item (which in your case happens on a remote computer) while still retrieving the next computer name from the file.
Now, coming back on the question "How do I correctly export a CSV file" which a better understanding of the pipeline, you might place Export-Csv within the foreach loop::
Get-Content .\Computers.txt |ForEach-Object {
[pscustomobject]#{
PSComputerName = $_
Model = "Model"
SerialNumber = '{0:000000}' -f (Get-Random 999999)
MediaType = "MydiaType"
} |Export-Csv .\Devices.csv -Append
}
As commented by #lit, this would require the -Append switch which might not be desired as every time you rerun your script this would append the results to the .\Devices.csv file.
Instead you might actually want do this:
Get-Content .\Computers.txt |ForEach-Object {
[pscustomobject]#{
PSComputerName = $_
Model = "Model"
SerialNumber = '{0:000000}' -f (Get-Random 999999)
MediaType = "MydiaType"
}
} |Export-Csv .\Devices.csv
Note the differences: the Export-Csv is placed outside the loop and the -Append switch is removed.
Explanation
As with e.g. the ForEach-Object cmdlet, the Export-Csv cmdlet has internally Begin, Process and End blocks.
In the Begin block (which runs when the pipeline is started), the Export-Csv cmdlet prepares the csv file with a header row etc. and overwrites any existing file.
In the Process block (which runs for each item received from the pipeline) it appends each line (data record) to the file.

Get Uptime on Each Computer in an Array, Select the machines with the most uptime, and remotely execute a Script on each Machine

The majority of this code was pulled from a blog online, but I think it's exactly the way I need to be tackling this. I want to get the top 4 machines from an OU based on uptime, and run a script that lives on each of the top 4 machines. I know that the problem involves the Array losing access to the Get-ADComputer properties, but I'm unsure of how to pass these new properties back to their original objects. This works as expected until it gets to the foreach loop at the end.
$scriptBlock={
$wmi = Get-WmiObject -Class Win32_OperatingSystem
($wmi.ConvertToDateTime($wmi.LocalDateTime) – $wmi.ConvertToDateTime($wmi.LastBootUpTime)).TotalHours
}
$UpTime = #()
Get-ADComputer -Filter 'ObjectClass -eq "Computer"' -SearchBase "OU=***,OU=***,OU=***,DC=***,DC=***" -SearchScope Subtree `
| ForEach-Object { $Uptime += `
(New-Object psobject -Property #{
"ComputerName" = $_.DNSHostName
"UpTimeHours" = (Invoke-Command -ComputerName $_.DNSHostName -ScriptBlock $scriptBlock)
}
)
}
$UpTime | Where-Object {$_.UpTimeHours -ne ""} | sort-object -property #{Expression="UpTimeHours";Descending=$true} | `
Select-Object -Property ComputerName,#{Name="UpTimeHours"; Expression = {$_.UpTimeHours.ToString("#.##")}} | Select-Object -First 4 |`
Format-Table -AutoSize -OutVariable $Top4.ToString()
foreach ($Server in $Top4.ComputerName) {
Invoke-Command -ComputerName $Server -ScriptBlock {HOSTNAME.EXE}
}
I'm not married to Invoke-Command in the last foreach but am having the same issues when I try to use psexec. Also, I'm running hostname.exe as a check to make sure I'm looping through the correct machines before I point it at my script.
Here's a streamlined version of your code, which heeds the comments on the question:
# Get all computers of interest.
$computers = Get-ADComputer -Filter 'ObjectClass -eq "Computer"' -SearchBase "OU=***,OU=***,OU=***,DC=***,DC=***" -SearchScope Subtree
# Get the computers' up-times in hours.
# The result will be [double] instances, but they're also decorated
# with .PSComputerName properties to identify the computer of origin.
$upTimes = Invoke-Command -ComputerName $computers.ConputerName {
((Get-Date) - (Get-CimInstance -Class Win32_OperatingSystem).LastBootUpTime).TotalHours
}
# Get the top 4 computers by up-time.
$top4 = $upTimes | Sort-Object -Descending | Select-Object -First 4
# Invoke a command on all these 4 computers in parallel.
Invoke-Command -ComputerName $top4.PSComputerName -ScriptBlock { HOSTNAME.EXE }

How to run Powershell on a list of computers

I'm trying to run a remote command on a list of computers that available in plain text file (1 computer per line) in a file named 1.txt available under c:\1\1.txt.
What I run the powershell script the variable $comp is being run as $comp instead of being changed to the computer name
$computers = Get-Content c:\1\1.txt
foreach ($comp in $computers){
$LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, #{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } }
echo $LicenseInfo, $comp
}
run the powershell command with the Computername $comp - where $comp will be changed everytime in the loop for another name of a computer available in the c:\1\1.txt file
The reason you are getting the Select-Object error is because echo is not a command in Powershell that is for batch. Powershell uses Write-Host There is more information here:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-host?view=powershell-4.0
As far as the code adding a delimiter switch to get-content will separate each computer name
Get-Content -Path c:\1\1.txt -Delimiter `r
The `r stands for a carriage return
Depending on how you want the output, you could try like this:
foreach ($comp in $computers) {
$LicenseInfo = Get-WmiObject SoftwareLicensingProduct -ComputerName $comp | Where-Object { $_.partialProductKey -and $_.ApplicationID -eq "55c92734-d682-4d71-983e-d6ec3f16059f" } | Select-Object PartialProductKey, Description, ProductKeyChannel, #{ N = "LicenseStatus"; E = { $lstat["$($_.LicenseStatus)"] } }
$LicenseInfo
$comp
}
The positional parameter error you're getting in your code is because you're giving echo variables and text, and the text isn't encapsulated in quotes.
You don't need echo or even Write-Host here if you just want to output the contents of your variables.

Powershell loop to call Disk Cleanup

I'm trying to loop through a list of Windows machines in the domain to call for Disk Cleanup however, because the way the list is returned it's not executing the ForEach statement with the name substituted. Can anyone provide some guidance on how to make this work?
Get-ADComputer -Filter {OperatingSystem -Like "*windows*"} -Property * | Format-Table Name | foreach {Echo "psexec \\$ cleanmgr /sagerun:1"}
something like this
$computers = get-Content c:\computers.txt
foreach ($computer in $computers){
if(!(Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{write-host "cannot reach $computer" -f red}
else {& \\$computer\C$\Windows\System32\cleanmgr.exe /sagerun:1}}
I got it working exactly the way I had wanted and with specific OU.
ForEach ($COMPUTER in (Get-ADComputer -Filter * | Where-Object {$_.DistinguishedName -Like "*OU=Employee's Computers,DC=company,DC=com"} | Select-Object -ExpandProperty Name)) { .\psexec \\$COMPUTER cleanmgr /sagerun:1 }

Powershell, Cleaning output data

I'm writing a script to get the Username of any user logged on to any computer. It works fine with 2 Exceptions.
Here is the code:
$computername = Get-Content 'I:\NodeList\SWSL.txt'
Remove-item "I:\NodeList\UsersPC.txt"
foreach ($computer in $computername)
{
if(Test-Connection -Computername $Computer -BufferSize 16 -Count 1 -ea 0)
{
$Uinfo = gwmi win32_computersystem -comp $computer | select Username,Caption #,Manufacturer
$Uinfo | Out-File -Filepath "I:\NodeList\UsersPC.txt" -Append
Write-Host $Uinfo
}else{
Write-Host $computer " Is offline, not responing to ping"
$computer + " Is offline!" | Out-File -Filepath "I:\NodeList\UsersPC.txt" -Append
}
}
First the Output is:
USername Caption
-------- -------
BINYAN\Charlie SYD-WS04
But I would only like to have:
Charlie SYD-WS04
The domain is always the same, so I just need the username and the computer name, and NOT the headings or the "---"
2nd Problem is, we are a render farm and all renders are processed on a user account Called "Render".
For those computers I only get the computer name, Username is Blank.
This user account is a Domain user, but not in an OU like the others (Sydney, Melbourne, Brisbane).
It resides in the default "Users" folder in AD.
You could remove the domain name using a regex that replaces everything until and including a \: '.*?\\'
You get rid of the heading using select -expand or using a foreach loop where you select the properties using $_.PROPERTY
So your statement could look like this:
$Uinfo = gwmi win32_computersystem -comp $computer |
foreach { '{0} {1}' -f ($_.Username -replace '.*?\\'), $_.Caption }
I have no answer for / I dont understand your second question.