mrdon
January 12, 2021, 5:09am
1
Hi.
I am trying to put below result into 1 table.
Server test.txt
------ --------
ServerA Exist
Server test.txt
------ --------
ServerB Not Exist
Below is the Code
$ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$Servers = Get-Content -Path C:\Users\suhail_asrulsani-ops\Desktop\PS\serverlist.txt
$dt = (Get-Date).ToString("ddMMyyyy_HHmmss")
$MultiSession = New-PSSession -ComputerName $Servers
$MyCommands =
{
$Server = hostname
$Path = "C:\test.txt"
If (Test-Path -Path $Path)
{
$Status = "Exist"
}
Else
{
$Status = "Not Exist"
}
$ourObject = New-Object -TypeName PsObject
$ourObject | Add-Member -MemberType NoteProperty -Name Server -Value $Server
$ourObject | Add-Member -MemberType NoteProperty -Name test.txt -Value $Status
$ourObject | Select-Object Server, test.txt | Format-Table -AutoSize
}
Invoke-Command -Session $MultiSession -ScriptBlock $MyCommands
Format-Table is what is really breaking things. There is much easier ways to be build an object, take a look at this example:
$Servers = Get-Content -Path C:\Users\suhail_asrulsani-ops\Desktop\PS\serverlist.txt
$MultiSession = New-PSSession -ComputerName $Servers
$MyCommands =
{
$Path = "C:\test.txt"
[PSCustomObject]@{
Date = (Get-Date).ToString("ddMMyyyy_HHmmss")
Server = $env:COMPUTERNAME
Path = $Path
Exists = Test-Path -Path $Path
}
}
$results = Invoke-Command -Session $MultiSession -ScriptBlock $MyCommands
$results | Format-Table
mrdon
January 12, 2021, 11:13am
3
Thanks Rob That works.
One last question,
How can I catch the error for this line of code. In case of the one of the server is offline.
I would like to catch the error for that offline server while continuing the script for the rest of the server in the list.
$MultiSession = New-PSSession -ComputerName $Servers
In order to catch errors for each server, you need to process them in a for loop rather than sending them as a batch. When you send a batch as a string array to a cmdlet, that cmdlet is processing them foreach($session in $ComputerName) {blah}, so you move it into your own loop to capture each failure. Recommend using a similar PSObject schema you can filter and find the failures and ensure that -ErrorAction stop is specified.
$ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$Servers = Get-Content -Path C:\Users\suhail_asrulsani-ops\Desktop\PS\serverlist.txt
$results = foreach ($server in $servers) {
try {
$session = New-PSSession -ComputerName $Server -ErrorAction Stop
$MyCommands =
{
$Path = "C:\test.txt"
[PSCustomObject]@{
Date = (Get-Date).ToString("ddMMyyyy_HHmmss")
Server = $env:COMPUTERNAME
Path = $Path
Exists = Test-Path -Path $Path
Status = 'Success'
}
}
Invoke-Command -Session $session -ScriptBlock $MyCommands -ErrorAction Stop
}
catch {
[PSCustomObject]@{
Date = (Get-Date).ToString("ddMMyyyy_HHmmss")
Server = $server
Path = $null
Exists = $null
Status = 'Fail: {0}' -f $_
}
}
}
$results