Try Catch not as intended - powershell

So I have this script working except I cannot get the computer name to display when there is an error, I understand that is because the computer is offline and the first Get computername cmd is an error as well, but I have tried multiple ways to perform this function with one thing or another not working.
gc "\\server\s$\powershellscripts\LabMachines\*.txt" | ForEach-Object{
Try{
$wdt = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_ -Ea Stop
$cdt = Get-Content "\\$_\C$\file\*.txt" -Ea Stop
}
Catch{
$wdt= $_
$cdt = 'Offline or NoFile'
}
$wdt | Select #{n='WorkStation';e={$_.PSComputerName}},#{n='Version';e={$cdt}}
} | ogv -Title 'Versions'
$host.enternestedprompt()
In a different attempt I have used this script, but this one below formats the information in rows instead of column like the first one.
Get-Content "\\server\s$\powershellscripts\LabMachines\*.txt" | ForEach-Object {
Try{
#{ComputerName=$_}
#{Version = Get-Content "\\$_\C$\file\*.txt" -Ea Stop}
}
Catch{
#{Version = 'Offline or NoFile' }
}
} #| out-file \\localhost\c$\users\public\Desktop\version.csv
Any attempt to take my script and merge it with one someone suggested to me "the second one" breaks it completely. To reiterate the top script give me the format output in columns I want but the bottom script gives the catch error "ComputerName Error" I need but has the output in harder to read row outfile.
Any suggestions?
Thanks.

Inside the catch block, $_ no longer refers to the pipeline item, but to the error that was caught.
Assign $_ to a different variable and you can reuse it inside the catch block:
Get-Content "\\server\s$\powershellscripts\LabMachines\*.txt" | ForEach-Object{
Try{
$ComputerName = $_
$wdt = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName -Ea Stop
$cdt = Get-Content "\\$_\C$\file\*.txt" -Ea Stop
}
Catch{
$wdt = #{PSComputerName = $ComputerName}
$cdt = 'Offline or NoFile'
}
$wdt | Select #{n='WorkStation';e={$_.PSComputerName}},#{n='Version';e={$cdt}}
}
Pipe to Export-Csv at the end if you want to output it to a CSV file:
} |Export-Csv C:\users\public\Desktop\version.csv -NoTypeInformation

I so I wanted to throw my finished product with a few additional things I learned. Here it is.
Function Version {
$i=1
$LabMachines = "\\server\s$\powershellscripts\LabMachines\*.txt"
$Total = 107 #a manual number for now
Get-Content $LabMachines | ForEach-Object{
Try{
$ComputerName=$_
$wdt = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName -Ea Stop
$cdt = Get-Content "\\$_\C$\file\*.txt" -Ea Stop
}
Catch{
$wdt = #{PSComputerName = $ComputerName}
$cdt = 'Offline'
}
$wdt | Select #{n='WorkStation';e={$_.PSComputerName}},#{n='Version';e={if($cdt){$cdt}else{"Error with Version.txt"}}}
$i++
$percent = [Math]::Round($i / $Total*100) } | Tee-Object -file \\localhost\c$\users\public\desktop\versions.csv |
Select #{n='%Complete';e={if(!($null)){$percent}else{"NULL"}}},
#{n='Number';e={if(!($null)){$i}else{"NULL"}}},
#{n='Computer';e={if(!($null)){$ComputerName}else{"NULL"}}},
#{n='Version';e={if($cdt){$cdt}else{"Error with Version.txt"}}} }
The changes I made in addition to the answer above was it will show progress in the console as a percent, number, computername, version txt as it completes. Also I made this into a function so we can run it and get the .csv file on our own desktop. To be fancier you could put in a line to do a line count to achieve the manual number I am using.
Thanks so much for the help I learned alot.

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.

How to pipe different output when using "Restart-Computer" powershell

I have a csv file
SERVERS|SEQUENCE|INDEX
ServerA| 1 | 1.1
ServerB| 1 | 2.1
ServerC| 2 | 3.1
And here is my Code
#importing csv into ps$
$csv = Import-Csv "sequencing.csv"
#Grouping & Sort data from csv
$objdata = $csv | Select SERVERS,SEQUENCE | Group SEQUENCE | Select #{n="SEQUENCE";e={$_.Name}},#{n="SERVERS";e={$_.Group | ForEach{$_.SERVERS}}} | Sort SEQUENCE
foreach ($d in $objdata)
{
$order = $d.SEQUENCE
$cNames = $d.SERVERS
if (Restart-Computer -ComputerName $cNames -Force -Wait -For Wmi -Delay 1 -ErrorAction SilentlyContinue)
{
write-host "$cNames is rebooting" -ForegroundColor Green
}
else
{
Write-Host "Unable to reboot $cNames remotely, Please do it manually" -ForegroundColor Red
}
}
I am trying to reboot multiple servers in sequence and piping the output through 2 different results.
From my code, all the servers will reboot but will output through the else statement.
Can anyone point me to the right direction?
Any help would be appreciated.
As Lee_Daily already pointed out, the Restart-Computer does not return anything. That means you will have to use a try/catch block.
To make sure that in the event of an error you actually enter the catch block, you need to set the ErrorAction parameter to Stop.
In your code, you show a csv to import that has the piping symbol | as delimiter, so you need to specify that on the Import-Csv cmdlet.
From your latest comment, I gather that you want to loop one computer at a time, instead of restarting multiple computers at once, so you will know which computer errors out.
Try:
# importing csv into ps$
$csv = Import-Csv "D:\sequencing.csv" -Delimiter '|'
# Grouping & Sort data from csv
$objdata = $csv | Select-Object SERVERS,SEQUENCE |
Group-Object SEQUENCE |
Select-Object #{Name = "SEQUENCE"; Expression = {$_.Name}},
#{Name = "SERVERS"; Expression = {$_.Group.SERVERS}} |
Sort-Object SEQUENCE
$objdata | ForEach-Object {
foreach ($server in $_.SERVERS) {
try {
Restart-Computer -ComputerName $server -Force -Wait -For Wmi -Delay 1 -ErrorAction Stop
Write-Host "Server $server is rebooting" -ForegroundColor Green
}
catch {
Write-Host "Unable to reboot $server remotely, Please do it manually" -ForegroundColor Red
}
}
}
Seeing your latest comment, I understand that you only want to reboot servers where the SEQUENCE value in the CSV is set to '1'. Correct?
Also, you want to restart the servers at the same time, but also want to be able to see what server did not restart. Maybe you can do that with running Restart-Computer -AsJob, but I believe that only works in PowerShell 5.1
Below code filters out all servers with SEQUENCE set to 1 and restarts them one at a time (as requested in your original question "I am trying to reboot multiple servers in sequence"):
# import csv data
$csv = Import-Csv "D:\sequencing.csv" -Delimiter '|' # change this to the delimiter actually used in the CSV !
# get the list of servers where SEQUENCE is set to '1'
$servers = $csv | Select-Object SERVERS,SEQUENCE |
Where-Object { $_.SEQUENCE.Trim() -eq '1' } |
ForEach-Object { $_.SERVERS.Trim() }
foreach ($server in $servers) {
try {
Restart-Computer -ComputerName $server -Force -Wait -For Wmi -Delay 1 -ErrorAction Stop
Write-Host "Server $server is rebooting" -ForegroundColor Green
}
catch {
Write-Host "Unable to reboot $server remotely, Please do it manually" -ForegroundColor Red
}
}

Get WMI Data From Multiple Computers and Export to CSV

So having some good old fashion Powershell frustrations today. What I need to do is this:
Get a list of computers from a file
Query those computers for "CSName" and "InstallDate" from Win32_OperatingSystem
Convert InstallDate into a useable date format.
Export all that to a .Csv
I've tried so many different iterations of my script. I run into 2 major issues. One is that I can't export and append to .Csv even with Export-Csv -Append. It just takes the first value and does nothing with the rest. The 2nd is that I can't get the datetime converter to work when piping |.
Here's a few samples of what I've tried - none of which work.
This sample simply errors a lot. Doesn't seem to carry $_ over from the WMI query in the pipe. It looks like it is trying to use data from the first pipe, but I'm not sure.
Get-Content -Path .\Computernames.txt | Foreach-Object {
gwmi Win32_OperatingSystem -ComputerName $_) |
Select-Object $_.CSName, $_.ConvertToDateTime($OS.InstallDate).ToShortDateString()
} | Export-Csv -Path Filename -Force -Append -NoTypeInformation
}
This one simply exports the first value and gives up on the rest when exporting .Csv
$Computers = Get-Content -Path .\Computernames.txt
foreach ($Computer in $Computers) {
echo $Computer
$OS = gwmi Win32_OperatingSystem -ComputerName $Computer
$OS | Select-Object
$OS.CSName,$OS.ConvertToDateTime($OS.InstallDate).ToShortDateString() |
Export-Csv -Path $Log.FullName -Append
}
This one does get the data, but when I try to select anything, I get null values, but I can echo just fine.
$OS = gwmi Win32_OperatingSystem -ComputerName $Computers
$OS | Foreach-Object {
Select-Object $_.CSName,$_.ConvertToDateTime($OS.InstallDate).ToShortDateString() |
Export-Csv -Path $Log.FullName -Force -Append -NoTypeInformation
}
This feels like it should be ridiculously simple. I can do this in C# with almost no effort, but I just can't get PS to do what I want. Any help would be much appreciated!
Here you go,
$Array = #() ## Create Array to hold the Data
$Computers = Get-Content -Path .\Computernames.txt
foreach ($Computer in $Computers)
{
$Result = "" | Select CSName,InstallDate ## Create Object to hold the data
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer
$Result.CSName = $OS.CSName ## Add CSName to line1
$Result.InstallDate = $OS.ConvertToDateTime($OS.InstallDate).ToShortDateString() ## Add InstallDate to line2
$Array += $Result ## Add the data to the array
}
$Array = Export-Csv c:\file.csv -NoTypeInformation

Writing all output to a file

I'm using the following code to get a list of machines with IP addresses. It prints out the hostname and IP address. If the host is offline, it says "$computername is offline." Here is the code:
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address
}
catch
{
"$computer is offline"
}
}
It works great and outputs the data like so:
Address IPV4Address
------- -----------
TESTMACHINE 192.168.1.1
TESTMACHINE2 192.168.1.2
TESTMACHINE3 is offline.
However no amount of trickery is allowing me to write all of this to a file, even though it's displaying like that in the console. It writes to a blank file or only writes the exception.
How can I capture this output exactly as it is?
You can create a custom powershell object using the same field names as the test-connection fields you are selecting and then export both success and failure to CSV. See below for an example:
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address | Export-Csv -Path .\ConnectionTest.csv -Append
}
catch
{
$Output = New-Object PSObject -Property #{
Address = $computer
IPV4Address = "Offline"
}
$Output | Export-Csv -Path .\ConnectionTest.csv -Append
}
}
In my style of writing scripts I'd use simple if..then..else loop. It seems most logical to me. You did try the "Out-File" switch after pipe, didn't you?... I have just run the below on localhost and some random name, and that worked just fine...
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
if (Test-Connection $computer -Count 1 -Quiet)
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address | Out-file -append "SomeFile.txt"
}
else
{
"$computer is offline" | Out-File -Append "SomeFile.txt"
}
}
Try this:
$csv = Get-Content TEST_MACHINES.csv
'' > foo.log
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address >> foo.log
}
catch
{
"$computer is offline" >> foo.log
}
}

powershell remove software from PC

(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null
I have following code which works perfectly. The only problem is that I wont to know if the software has been removed or not.This doesn't tells me but the code below does.
This way works for me.
$software = Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }
$soft = $software.Uninstall();
$n = $software.ReturnValue;
if ( $n -eq 0 ){
SOFTWARE HAS BEEN REMOVED.
}
my question is that how do i tell if the software has been removed or not.
using this code.
(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null
You have to check the ReturnValue property. When you pipe to Out-Null you are suppressing the output of the operation and there's no way to tell what happened, unless you issue a second call to find if it returns the software in question.
I recommend using the Filter parameter (instead of using Where-Object) to query the software on the server. To be safe you should also pipe the results to the Foreach-Object cmdlet, you never know how many software objects you get back due to the match operation (and you call the Uninstall method as if the result is one object only):
Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -Filter "Name LIKE '%$softwareName%'" | Foreach-Object {
Write-Host "Uninstalling: $($_.Name)"
$rv = $_.Uninstall().ReturnValue
if($rv -eq 0)
{
"$($_.Name) uninstalled successfully"
} # Changed this round bracket to a squigly one to prperly close the scriptblock for "if"
else
{
"There was an error ($rv) uninstalling $($_.Name)"
}
}