Welcome › Forums › General PowerShell Q&A › Script causes ISE to crash
- This topic has 2 replies, 2 voices, and was last updated 1 month ago by
Participant.
-
AuthorPosts
-
-
December 17, 2020 at 10:24 am #280494
I downloaded the Get-NetSession.ps1 script from the TechNet Script Center Gallery, (https://gallery.technet.microsoft.com/scriptcenter/View-Net-Sessions-locally-d6eb2ba0) but I needed the number of open files, so I substituted SESSION_INFO_10 for SESSION_INFO_1 and defined the two extra fields. It runs and returns the open files, but it crashes ISE right after that.
I added code to get the user DisplayName, Telephone and Extension. Also added code to format the SessionTime and IdleTime. Still need to add code to display the OpenFiles correctly.
Does anyone have any ideas why its crashing ISE?
Running on a Windows 10 Enterprise Edition workstation.
Thanks.
PowerShell123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269Function Get-NetSession {<#.SYNOPSISQueries the remote system for all net sessions.DESCRIPTIONQueries the remote system for all net sessions.PARAMETER ComputernameComputer to query for net sessions.PARAMETER UsernameSpecifies a user to look for in the net sessions.PARAMETER IncludeSelfIncludes the current user session used to run this command.NOTESName: Get-NetSessionAuthor: Boe ProxVersion History:1.1 //Boe Prox - 1 August 2016- Added IncludeSelf parameter to include displaying the session created from command otherwisethis data is not presented- Bug fixes1.0 //Boe Prox - 28 July 2016- Initial build.EXAMPLEGet-NetSession -Computername Server1Computername : Server1SourceComputer : Workstation1SourceIPAddress : 192.168.2.56Username : bobsmithSessionTime : 0IdleTime : 0Computername : Server1SourceComputer : Workstation2SourceIPAddress : 192.168.2.110Username : joeuserSessionTime : 348607IdleTime : 345850Description-----------Returns all net sessions on Server1#>[cmdletbinding()]Param ([parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)][string[]]$Computername,[parameter()][string]$Username = '',[parameter()][switch]$IncludeSelf)Begin {If ($PSBoundParameters.ContainsKey('Debug')) {$DebugPreference = 'Continue'}If (-NOT $PSBoundParameters.ContainsKey('IncludeSelf')) {$Hostname = "$($env:COMPUTERNAME).$($env:USERDNSDOMAIN)"Write-Verbose "Excluding $Hostname and $($env:USERNAME)"}#region ReflectionTry {[void][Net.Session]}Catch {Write-Verbose "Building pinvoke via reflection"#region Module Builder$Domain = [AppDomain]::CurrentDomain$DynAssembly = New-Object System.Reflection.AssemblyName('NetSession')$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) # Only run in memory$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('NetSessionModule', $False)#endregion Module Builder#region Custom Attribute Builder$ctor = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructor(@([System.Runtime.InteropServices.UnmanagedType]))$CustomAttribute = [System.Runtime.InteropServices.UnmanagedType]::LPWStr$CustomAttributeBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder -ArgumentList $ctor, $CustomAttribute#endregion Custom Attribute Builder#region Struct#region SESSION_INFO_1$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'$STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SESSION_INFO_1', $Attributes, [System.ValueType], 8, 0x0)$Field = $STRUCT_TypeBuilder.DefineField('OriginatingHost', [string], 'Public')$Field.SetCustomAttribute($CustomAttributeBuilder)$Field = $STRUCT_TypeBuilder.DefineField('DomainUser', [string], 'Public')$Field.SetCustomAttribute($CustomAttributeBuilder)[void]$STRUCT_TypeBuilder.DefineField('OpenFiles', [uint32], 'Public')[void]$STRUCT_TypeBuilder.DefineField('SessionTime', [uint32], 'Public')[void]$STRUCT_TypeBuilder.DefineField('IdleTime', [uint32], 'Public')[void]$STRUCT_TypeBuilder.DefineField('UserFlags', [uint32], 'Public')[void]$STRUCT_TypeBuilder.CreateType()#endregion SESSION_INFO_1#endregion Struct$TypeBuilder = $ModuleBuilder.DefineType('Net.Session', 'Public, Class')#region Methods#region NetSessionEnum Method$PInvokeMethod = $TypeBuilder.DefineMethod('NetSessionEnum', #Method Name[Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes[int32], #Method Return Type[Type[]] @([string],[string],[string],[int32],[intptr].MakeByRefType(),[int],[int32].MakeByRefType(),[int32].MakeByRefType(),[int32].MakeByRefType()) #Method Parameters)#Define first three parameters with custom attributes1..3 | ForEach {$Parameter = $PInvokeMethod.DefineParameter($_,[System.Reflection.ParameterAttributes]::In,$Null)$Parameter.SetCustomAttribute($CustomAttributeBuilder)}$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))$FieldArray = [Reflection.FieldInfo[]] @([Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),[Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')[Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')[Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig'))$FieldValueArray = [Object[]] @('NetSessionEnum', #CASE SENSITIVE!!$True,$True,$True)$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,@('Netapi32.dll'),$FieldArray,$FieldValueArray)$PInvokeMethod.SetCustomAttribute($CustomAttribute)#endregion NetSessionEnum Method#region NetApiBufferFree Method$PInvokeMethod = $TypeBuilder.DefineMethod('NetApiBufferFree', #Method Name[Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes[int], #Method Return Type[Type[]] @([intptr]) #Method Parameters)$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))$FieldArray = [Reflection.FieldInfo[]] @([Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),[Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')[Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')[Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig'))$FieldValueArray = [Object[]] @('NetApiBufferFree', #CASE SENSITIVE!!$True,$True,$True)$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,@('Netapi32.dll'),$FieldArray,$FieldValueArray)$PInvokeMethod.SetCustomAttribute($CustomAttribute)#endregion NetApiBufferFree Method#endregion Methods[void]$TypeBuilder.CreateType()}#endregion Reflection}Process {ForEach ($Computer in $Computername) {Write-Verbose "Scanning $Computer"$SessionInfo1 = New-Object -TypeName SESSION_INFO_1$SessionInfo1Size = [System.Runtime.InteropServices.Marshal]::SizeOf($SessionInfo1)$Buffer = [IntPtr]::Zero[int32]$EntriesRead = 0[int32]$TotalEntries = 0[int32]$ResumeHandle = 0$Return = [Net.Session]::NetSessionEnum($Computer,"",$Username,10,[ref]$Buffer,-1,[ref]$EntriesRead,[ref]$TotalEntries,[ref]$ResumeHandle)$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()If ([System.IntPtr]::Size -eq 4) {$BufferOffset = $Buffer.ToInt32()}Else {$BufferOffset = $Buffer.ToInt64()}For ($Count = 0; ($Count -lt $EntriesRead); $Count++){$NewBuffer = New-Object System.Intptr -ArgumentList $BufferOffset$Info = [System.Runtime.Interopservices.Marshal]::PtrToStructure($NewBuffer,[type]$SessionInfo1.GetType())$Info | ForEach {$IP = $_.OriginatingHost.Trim('\\')Try {$ResolvedName = [Net.DNS]::GetHostByAddress($IP).HostName}Catch {$ResolvedName = 'N/A'}$Object = [pscustomobject]@{Computername = $ComputerSourceComputer = $ResolvedNameSourceIPAddress = $IPUsername = $_.DomainUserDisplayName = (Get-ADUser -Identity $_.DomainUser -Properties displayname).displaynameTelephone = (Get-ADUser -Identity $_.DomainUser -Properties telephoneNumber).telephoneNumberExtension = (Get-ADUser -Identity $_.DomainUser -Properties extensionAttribute3).extensionAttribute3OpenFiles = "$($_.OpenFiles)" ## Added to script ##SessionTime = [TimeSpan]::FromSeconds($_.SessionTime).ToString('hh\:mm\:ss')IdleTime = [TimeSpan]::FromSeconds($_.IdleTime).ToString('hh\:mm\:ss')}$Object.pstypenames.insert(0,'Net.SessionInformation')If (($PSBoundParameters.ContainsKey('IncludeSelf'))) {$Object}ElseIf (-NOT ((($ResolvedName -eq $Hostname) -OR ($IP -eq $env:COMPUTERNAME)) -AND ($_.DomainUser -eq $env:USERNAME))) {$Object}}$BufferOffset = $BufferOffset + $SessionInfo1Size}[void][Net.Session]::NetApiBufferFree($Buffer)}}End {}}-
This topic was modified 1 month ago by
grokkit. Reason: code formatting - please read the guide
-
This topic was modified 1 month ago by
-
December 17, 2020 at 11:00 am #280509
PowerShell ISE is deprecated. Development of the ISE ended along with development of Windows PowerShell (v5.1), which was dropped in favor of the open-source PowerShell Core in 2017. No one is working on it; the problems with it won’t be fixed.
Additionally, the PowerShell ISE console is not a ‘real’ console, but is effectively an emulation of a console running inside a Win32 application (it’s fake). There are significant execution differences between the ISE console and actual PowerShell, which are now amplified by the differences between Windows PowerShell and PowerShell Core, and three more years of development.
So, ISE is not a valid test environment. You should test your scripts against the version of PowerShell that you have installed on your system, in a development environment. VSCode is the recommended development tool.
-
December 17, 2020 at 11:10 am #280515
I do have VSCode installed on my workstation, but since I started with ISE and don’t code as often as I wish, it’s my fallback.
Let me try to run the script in VSCode.
Also, like I said I don’t code often enough, I still haven’t figured out how to display the OpenFiles correctly. It reports 37434 files open, when the user only has 2 files open. Any help would be appreciated.
Thanks,
-
-
AuthorPosts
- You must be logged in to reply to this topic.