Forum Discussion

deepak410's avatar
deepak410
Copper Contributor
Nov 22, 2022

Powershell pssesion

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

}

else

{

$res += "$computers - OFFLINE"

}}

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

  •  

    PSSession:
    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=powershell-7.3
    You can remove the session the line after the invoke-command so that way you only try to remove it if it exists.

     

    Export:
    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
    True

    Determining the type of the property:

    PS C:\> $a = Get-LocalUser                                                                                              PS C:\> $a[0].Enabled
    False
    PS C:\> $a[0].Enabled.GetType()
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     Boolean                                  System.ValueType

     

    I hope this helps. Have fun scipting.

     

    deepak410 

Share

Resources