Powershell pssesion

Copper Contributor

Below my code, I want to know if I created a  pssesion on remote computer, what will happen if i will not end the pssesion? what will be possible impact on remote computer? or session will automatically terminated? In the last I have used exit-pssesion but I don't know it is working or not?


Second: for the else statement where the if statement is not fulfilled the result is not printed in  csv file. having a error "does not contain a method named 'op_Addition' "


$computers = Get-Content -Path E:\Newfolder\Input\List_computers.txt

Foreach ($computers in $computers)


If (Test-Connection -ComputerName $computers -Quiet  )


$password = convertTo-SecureString "12345678" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential ("domain\abc", $password)

$session = New-PSSession -ComputerName $computers -Credential $cred

 $command = {Get-LocalUser| where-Object -Property Enabled -EQ True | Select-Object -Property  Name, Enabled, Description }

$res = Invoke-Command -Session $session -ScriptBlock $command




$res += "$computers - OFFLINE"


$res | Export-Csv \\\e$\usercheckResult_$((Get-Date).ToString('yyyyMMdd_HHmmss')).csv -NoTypeInformation | Start-Sleep -Seconds 2 | Exit-PSSession

1 Reply


Exit-PSSession is used when you have used Enter-PSSession and want to end that session.
To terminate the session you have created using New-PSSession use Remove-PSSession documented here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/remove-pssession?view=...
You can remove the session the line after the invoke-command so that way you only try to remove it if it exists.


Your export is fine, just remove the pipe and everything after it.


Extra bit:
In your Get-LocalUser you use 'True' for a comparison. While it works because PowerShell automatically type casts, I recommend comparing with $True.

PowerShell turning a boolean into a string:

PS C:\> [string]$true

Determining the type of the property:

PS C:\> $a = Get-LocalUser                                                                                              PS C:\> $a[0].Enabled
PS C:\> $a[0].Enabled.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Boolean                                  System.ValueType


I hope this helps. Have fun scipting.