PsRunspace.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 |
function Add-PsCommand { <# .Synopsis Add a command to a [System.Management.Automation.PowerShell] instance .Description Used by Invoke-Thread Uses AddScript() or AddStatement() and AddCommand() depending on the command .EXAMPLE [powershell]::Create() | Add-PsCommand -Command 'Write-Output' Add a command by sending a Cmdlet name to the -Command parameter #> param( # Powershell interface to add the Command to [Parameter(ValueFromPipeline = $true)] [powershell[]]$PowershellInterface, <# Command to add to the Powershell interface This can be a scriptblock object, or a string that specifies a: Alias Function (the name of the function) ExternalScript (the path to the .ps1 file) All, Application, Cmdlet, Configuration, Filter, or Script #> [Parameter(Position = 0)] $Command, # Output from Get-PsCommandInfo # Optional, to improve performance if it will be re-used for multiple calls of Add-PsCommand [pscustomobject]$CommandInfo, # Add Commands rather than their definitions [switch]$Force, # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) begin { if ($CommandInfo -eq $null) { $CommandInfo = Get-PsCommandInfo -Command $Command } $LogParams = @{ Type = $DebugOutputStream ThisHostname = $TodaysHostname } } process { ForEach ($ThisPowershell in $PowershellInterface) { switch ($CommandInfo.CommandType) { 'Alias' { # Resolve the alias to its command and start from the beginning with that command. $CommandInfo = Get-PsCommandInfo -Command $CommandInfo.CommandInfo.Definition -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname $null = Add-PsCommand -Command $CommandInfo.CommandInfo.Definition -CommandInfo $CommandInfo -PowershellInterface $ThisPowerShell -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname } 'Function' { if ($Force) { Write-LogMsg @LogParams -Text " # Adding command '$Command' of type '$($CommandInfo.CommandType)' (treating it as a Command instead of a Function because -Force was used)" # If the type is All, Application, Cmdlet, Configuration, Filter, or Script then run the command as-is Write-LogMsg @LogParams -Text " `$PowershellInterface.AddStatement().AddCommand('$Command')" $null = $ThisPowershell.AddStatement().AddCommand($Command) } else { # Add the definitions of the function # BUG: Look at the definition of Get-Member for example, it is not in a ScriptModule so its definition is not PowerShell code [string]$ThisFunction = "function $($CommandInfo.CommandInfo.Name) {`r`n$($CommandInfo.CommandInfo.Definition)`r`n}" Write-LogMsg @LogParams -Text " # Adding Script (the Definition of a Function, `$CommandInfo.CommandInfo.Definition not expanded below for brevity)" ##Write-LogMsg @LogParams -Text " `$PowershellInterface.AddScript('function $($CommandInfo.CommandInfo.Name) { `$CommandInfo.CommandInfo.Definition }')" Write-LogMsg @LogParams -Text " `$PowershellInterface.AddScript('$ThisFunction')" $null = $ThisPowershell.AddScript($ThisFunction) } } 'ExternalScript' { Write-LogMsg @LogParams -Text " # Adding Script (the ScriptBlock of an ExternalScript, `$CommandInfo.ScriptBlock not expanded below for brevity)" ##Write-LogMsg @LogParams -Text " `$PowershellInterface.AddScript(`"`$(`$CommandInfo.ScriptBlock)`") # " Write-LogMsg @LogParams -Text " `$PowershellInterface.AddScript('$($CommandInfo.ScriptBlock)')" $null = $ThisPowershell.AddScript($CommandInfo.ScriptBlock) } 'ScriptBlock' { Write-LogMsg @LogParams -Text " # Adding Script (a ScriptBlock, not expanded below for brevity)" ##Write-LogMsg @LogParams -Text " `$PowershellInterface.AddScript(`"`$Command`") Write-LogMsg @LogParams -Text " `$PowershellInterface.AddScript('$Command')" $null = $ThisPowershell.AddScript($Command) } default { Write-LogMsg @LogParams -Text " # Adding command '$Command' of type '$($CommandInfo.CommandType)'" # If the type is All, Application, Cmdlet, Configuration, Filter, or Script then run the command as-is Write-LogMsg @LogParams -Text " `$PowershellInterface.AddStatement().AddCommand('$Command')" $null = $ThisPowershell.AddStatement().AddCommand($Command) } } } } } function Add-PsModule { <# .Synopsis Import a Module in a [System.Management.Automation.Runspaces.InitialSessionState] instance .Description Used by Add-PsCommand Uses ImportPSModule() or ImportPSModulesFromPath() depending on the module .EXAMPLE $InitialSessionState = [system.management.automation.runspaces.initialsessionstate]::CreateDefault() Add-PsModule -InitialSessionState $InitialSessionState -ModuleInfo $ModuleInfo #> param( # Powershell interface to add the Command to [Parameter(Mandatory)] [System.Management.Automation.Runspaces.InitialSessionState]$InitialSessionState, <# ModuleInfo object for the module to add to the Powershell interface #> [Parameter( Position = 0 )] [System.Management.Automation.PSModuleInfo[]]$ModuleInfo, # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) begin { $LogParams = @{ Type = $DebugOutputStream ThisHostname = $TodaysHostname } } process { ForEach ($ThisModule in $ModuleInfo) { switch ($ThisModule.ModuleType) { 'Binary' { Write-LogMsg @LogParams -Text " `$InitialSessionState.ImportPSModule('$($ThisModule.Name)')" $InitialSessionState.ImportPSModule($ThisModule.Name) } 'Script' { $ModulePath = Split-Path -Path $ThisModule.Path -Parent Write-LogMsg @LogParams -Text " `$InitialSessionState.ImportPSModulesFromPath('$ModulePath')" $InitialSessionState.ImportPSModulesFromPath($ModulePath) } 'Manifest' { $ModulePath = Split-Path -Path $ThisModule.Path -Parent Write-LogMsg @LogParams -Text " `$InitialSessionState.ImportPSModulesFromPath('$ModulePath')" $InitialSessionState.ImportPSModulesFromPath($ModulePath) } default { # Scriptblocks or Functions not from modules will have no module to import so ModuleInfo will be null } } } } } function Convert-FromPsCommandInfoToString { param ( [Parameter ( Mandatory, Position = 0 )] [PSCustomObject[]]$CommandInfo, # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) process { ForEach ($ThisCmd in $CommandInfo) { switch ($ThisCmd.CommandType) { 'Alias' { # Resolve the alias to its command and start from the beginning with that command $ThisCmd = Get-PsCommandInfo -Command $ThisCmd.CommandInfo.Definition -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname Convert-FromPsCommandInfoToString -CommandInfo $ThisCmd -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname } 'Function' { "function $($ThisCmd.CommandInfo.Name) {`r`n$($ThisCmd.CommandInfo.Definition)`r`n}" } 'ExternalScript' { "$($ThisCmd.ScriptBlock)" #"$($ThisCmd.CommandInfo.ScriptBlock)" #"$Command" } 'ScriptBlock' { "$Command" } default { "$Command" } } } } } function Expand-PsCommandInfo { <# .SYNOPSIS Return the original PsCommandInfo object as well as CommandInfo objects for any nested commands #> param ( # CommandInfo object for the command whose nested command names to return [PSCustomObject]$PsCommandInfo, # Cache of already identified CommmandInfo objects [hashtable]$Cache = [hashtable]::Synchronized(@{}), # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) # Add the first object to the cache if (-not $PsCommandInfo.CommandInfo.Name) { $PsCommandInfo } else { $Cache[$PsCommandInfo.CommandInfo.Name] = $PsCommandInfo } # Tokenize the function definition $PsTokens = $null $TokenizerErrors = $null $AbstractSyntaxTree = [System.Management.Automation.Language.Parser]::ParseInput( # We need the property which contains tokenizable PowerShell # For a function in a ScriptModule, the definition and scriptblock properties are the same # For an ExternalScript, the definition is the filepath and the scriptblock is tokenizable powershell # This is why the Scriptblock property has been chosen #$PsCommandInfo.CommandInfo.Definition, $PsCommandInfo.CommandInfo.Scriptblock, [ref]$PsTokens, [ref]$TokenizerErrors ) # Get all nested tokens $AllPsTokens = Expand-PsToken -InputObject $PsTokens # Find any other functions we also need to add $CommandTokens = $AllPsTokens | Where-Object -FilterScript { $_.Kind -eq 'Generic' -and $_.TokenFlags.HasFlag([System.Management.Automation.Language.TokenFlags]::CommandName) } # Add the definitions of those functions if available # TODO: Add modules if available? Not needed at this time but maybe later ForEach ($ThisCommandToken in $CommandTokens) { if ( -not $Cache[$ThisCommandToken.Value] -and $ThisCommandToken.Value -notmatch '[\.\\]' # This excludes any file paths since they are not PowerShell commands with tokenizable definitions (they contain \ or .) ) { $TokenCommandInfo = Get-PsCommandInfo -Command $ThisCommandToken.Value -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname $Cache[$ThisCommandToken.Value] = $TokenCommandInfo # Suppress the output of the Expand-PsCommandInfo function because we will instead be using the updated cache contents # This way the results are already deduplicated for us by the hashtable $null = Expand-PsCommandInfo -PsCommandInfo $TokenCommandInfo -Cache $Cache -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname } } # Output the objects in the cache ForEach ($ThisKey in $Cache.Keys) { $Cache[$ThisKey] } } function Expand-PsToken { <# .SYNOPSIS Recursively get nested tokens .DESCRIPTION Recursively emits all tokens embedded in a token of type "StringExpandable" The original token is also emitted. .EXAMPLE $Tokens = $null $TokenizerErrors = $null $AbstractSyntaxTree = [System.Management.Automation.Language.Parser]::ParseInput( [string]$Code, [ref]$Tokens, [ref]$TokenizerErrors ) $Tokens | Expand-PsToken Return all tokens nested inside the provided $Code #> param ( # Management.Automation.Language.StringExpandableToken or # Management.Automation.Language.Token [Parameter( Mandatory, Position = 0 )] [psobject]$InputObject ) process { if ($InputObject.GetType().FullName -eq 'Management.Automation.Language.StringExpandableToken]') { ForEach ($ThisToken in $InputObject.NestedTokens) { if ($ThisToken) { Expand-PsToken -InputObject $ThisToken } } } $InputObject } } function Get-PsCommandInfo { <# .Synopsis Get info about a PowerShell command .Description Used by Split-Thread, Invoke-Thread, and Add-PsCommand Determine whether the Command is a [System.Management.Automation.ScriptBlock] object If not, passes it to the Name parameter of Get-Command .EXAMPLE The following demonstrates sending a Cmdlet name to the -Command parameter Get-PsCommandInfo -Command 'Write-Output' #> param( <# Command to retrieve info on This can be a scriptblock object, or a string that specifies an: Alias Function (the name of the function) ExternalScript (the path to the .ps1 file) All, Application, Cmdlet, Configuration, Filter, or Script #> $Command, # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) $LogParams = @{ Type = $DebugOutputStream ThisHostname = $TodaysHostname } if ($Command.GetType().FullName -eq 'System.Management.Automation.ScriptBlock') { [string]$CommandType = 'ScriptBlock' } else { $CommandInfo = Get-Command $Command -ErrorAction SilentlyContinue [string]$CommandType = $CommandInfo.CommandType if ($CommandInfo.Source -like "*\*") { $ModuleInfo = Get-Module -Name $CommandInfo.Source -ListAvailable -ErrorAction SilentlyContinue } else { if ($CommandInfo.Source) { Write-LogMsg @LogParams -Text " Get-Module -Name '$($CommandInfo.Source)'" $ModuleInfo = Get-Module -Name $CommandInfo.Source -ErrorAction SilentlyContinue } } } if ($ModuleInfo.Path -like "*.ps1") { $ModuleInfo = $null $SourceModuleName = $null } else { $SourceModuleName = $CommandInfo.Source } Write-LogMsg @LogParams -Text " $Command is a $CommandType" [pscustomobject]@{ CommandInfo = $CommandInfo ModuleInfo = $ModuleInfo CommandType = $CommandType SourceModuleDefinition = $ModuleInfo.Definition SourceModuleName = $SourceModuleName } } function Open-Thread { <# .Synopsis Prepares each thread so it is ready to execute a command and capture the output streams .Description Used by Split-Thread For each InputObject an instance will be created of [System.Management.Automation.PowerShell] Then a series of commands will be run to enable the specified output streams (all by default) #> Param( # Objects to pass to the Command as an argument or parameter [Parameter( ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] $InputObject, # .Net Framework runspace pool to use for the threads [Parameter( Mandatory = $true )] [System.Management.Automation.Runspaces.RunspacePool]$RunspacePool, <# Name of a property (whose value is a string) that exists on each $InputObject It will be used to represent the object in text form If left null, the object's ToString() method will be used instead. #> [string]$ObjectStringProperty, # PowerShell Command or Script to run against each InputObject [Parameter(Mandatory = $true)] $Command, # Output from Get-PsCommandInfo [pscustomobject[]]$CommandInfo, # Named parameter of the Command to pass InputObject to # If this is not specified, InputObject will be passed to the Command as an argument [string]$InputParameter = $null, <# Parameters to add to the Command Each parameter is a name-value pair in the hashtable: @{"ParameterName" = "Value"} @{"ParameterName" = "Value" ; "ParameterTwo" = "Value2"} #> [HashTable]$AddParam = @{}, # Switches to add to the Command [string[]]$AddSwitch = @(), # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) begin { $LogParams = @{ Type = $DebugOutputStream ThisHostname = $TodaysHostname } [int64]$CurrentObjectIndex = 0 $ThreadCount = @($InputObject).Count Write-LogMsg @LogParams -Text " # Received $(($CommandInfo | Measure-Object).Count) PsCommandInfos from Split-Thread for '$Command'" if ($CommandInfo) { # Begin to build the command that the script will run with all its parameters if (Test-Path $Command -ErrorAction SilentlyContinue) { # If $Command is a valid file path, dot-source it and wrap it in single quotes to handle spaces $CommandStringForScriptDefinition = [System.Text.StringBuilder]::new(". '$Command'") } else { $CommandStringForScriptDefinition = [System.Text.StringBuilder]::new($Command) } # Build the param block of the script. Along the way, add any necessary parameters and switches # Avoided using AppendJoin for slight performance and code readability penalty due to lack of support in PS 5.1 $ScriptDefinition = [System.Text.StringBuilder]::new() $null = $ScriptDefinition.AppendLine('param (') If ([string]::IsNullOrEmpty($InputParameter)) { $null = $ScriptDefinition.Append(" `$PsRunspaceArgument1") $null = $CommandStringForScriptDefinition.Append(" `$PsRunspaceArgument1") } else { $null = $ScriptDefinition.Append(" `$$InputParameter") $null = $CommandStringForScriptDefinition.Append(" -$InputParameter `$$InputParameter") } ForEach ($ThisKey in $AddParam.Keys) { $null = $ScriptDefinition.Append(",`r`n `$$ThisKey") $null = $CommandStringForScriptDefinition.Append(" -$ThisKey `$$ThisKey") } ForEach ($ThisSwitch in $AddSwitch) { $null = $ScriptDefinition.Append(",`r`n [switch]`$", $ThisSwitch) $null = $CommandStringForScriptDefinition.Append(" -$ThisSwitch") } $null = $ScriptDefinition.AppendLine("`r`n)`r`n") Convert-FromPsCommandInfoToString -CommandInfo $CommandInfo -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname | ForEach-Object { $null = $ScriptDefinition.AppendLine("`r`n$_") } $null = $ScriptDefinition.AppendLine() $CommandStringForScriptDefinition | ForEach-Object { $null = $ScriptDefinition.AppendLine("`r`n$_") } $null = $ScriptDefinition.AppendLine() $ScriptString = $ScriptDefinition.ToString() # Remove blank lines # Commented out due to risk of unintended side effects: what if the code includes a here-string that requires blank lines, etc) #while ( $ScriptString -match '\r\n\r\n' ) { # $ScriptString = $ScriptString -replace "`r`n`r`n", "`r`n" #} $ScriptBlock = [scriptblock]::Create($ScriptString) } } process { ForEach ($Object in $InputObject) { $CurrentObjectIndex++ if ($ObjectStringProperty -ne '') { [string]$ObjectString = $Object."$ObjectStringProperty" } else { [string]$ObjectString = $Object.ToString() } Write-LogMsg @LogParams -Text " `$PowershellInterface = [powershell]::Create() # for '$Command' on '$ObjectString'" $PowershellInterface = [powershell]::Create() Write-LogMsg @LogParams -Text " `$PowershellInterface.RunspacePool = `$RunspacePool # for '$Command' on '$ObjectString'" $PowershellInterface.RunspacePool = $RunspacePool # Do I need this one? What commands would be in there? Write-LogMsg @LogParams -Text " `$PowershellInterface.Commands.Clear() # for '$Command' on '$ObjectString'" $null = $PowershellInterface.Commands.Clear() if ($ScriptBlock) { #$null = Add-PsCommand -Command $ScriptBlock -PowershellInterface $PowershellInterface -Force -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname $null = Add-PsCommand -Command $ScriptBlock -PowershellInterface $PowershellInterface -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname } else { $null = Add-PsCommand -Command $Command -PowershellInterface $PowershellInterface -Force -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname } # Prepare to pass $InputObject into the runspace as a parameter not an argument # Do this even if we end up passing it as an argument to the command inside the runspace If ([string]::IsNullOrEmpty($InputParameter)) { $InputParameter = 'PsRunspaceArgument1' } Write-LogMsg @LogParams -Text " `$PowershellInterface.AddParameter('$InputParameter', '$ObjectString') # for '$Command' on '$ObjectString'" $null = $PowershellInterface.AddParameter($InputParameter, $Object) <#NormallyCommentThisForPerformanceOptimization#>$InputParameterStringForDebug = "-$InputParameter '$ObjectString'" $AdditionalParameters = @() $AdditionalParameters = ForEach ($Key in $AddParam.Keys) { Write-LogMsg @LogParams -Text " `$PowershellInterface.AddParameter('$Key', '$($AddParam.$key)') # for '$Command' on '$ObjectString'" $null = $PowershellInterface.AddParameter($Key, $AddParam.$key) <#NormallyCommentThisForPerformanceOptimization#>"-$Key '$($AddParam.$key)'" } $AdditionalParametersString = $AdditionalParameters -join ' ' $Switches = @() $Switches = ForEach ($Switch in $AddSwitch) { Write-LogMsg @LogParams -Text " `$PowershellInterface.AddParameter('$Switch') # for '$Command' on '$ObjectString'" $null = $PowershellInterface.AddParameter($Switch) <#NormallyCommentThisForPerformanceOptimization#>"-$Switch" } $SwitchParameterString = $Switches -join ' ' $StatusString = "Invoking thread $CurrentObjectIndex`: $Command $InputParameterStringForDebug $AdditionalParametersString $SwitchParameterString" $Progress = @{ Activity = $StatusString PercentComplete = $CurrentObjectIndex / $ThreadCount * 100 Status = "$($ThreadCount - $CurrentObjectIndex) remaining" } Write-Progress @Progress Write-LogMsg @LogParams -Text " `$Handle = `$PowershellInterface.BeginInvoke() # for '$Command' on '$ObjectString'" $Handle = $PowershellInterface.BeginInvoke() [PSCustomObject]@{ Handle = $Handle PowerShellInterface = $PowershellInterface Object = $Object ObjectString = $ObjectString Index = $CurrentObjectIndex Command = "$Command" } } } end { Write-Progress -Activity 'Completed' -Completed } } function Split-Thread { <# .Synopsis Split a command for a collection of input objects into multiple threads for asynchronous processing .Description The specified command will be run for each input object in a separate powershell instance with its own runspace These runspaces are part of the same runspace pool inside the same powershell.exe process .EXAMPLE The following demonstrates sending a Cmdlet name to the -Command parameter $InputObject | Split-Thread -Command 'Write-Output' .EXAMPLE The following demonstrates sending a scriptblock to the -Command parameter $InputObject | Split-Thread -Command [scriptblock]::create("Write-Output `$args[0]") .EXAMPLE The following demonstrates sending a script file path to the -Command parameter $InputObject | Split-Thread -Command "C:\Test-Command.ps1" .EXAMPLE The following demonstrates sending a function to the -Command parameter $InputObject | Split-Thread -Command 'Test-Function' .EXAMPLE The following demonstrates the -AddParam parameter $InputObject | Split-Thread -Command "Get-Service" -InputParameter ComputerName -AddParam @{"Name" = "BITS"} .EXAMPLE The following demonstrates the -AddSwitch parameter $InputObject | Split-Thread -Command "Get-Service" -AddSwitch @('RequiredServices','DependentServices') .EXAMPLE The following demonstrates the use of a threadsafe hashtable to store results The hastable can be accessed and updated from inside each runspace $ThreadsafeHashtable = [hashtable]::Synchronized(@{}) $InputObject | Split-Thread -Command "Fake-Function" -InputParameter ComputerName -AddParam @{"ResultHashTableParameter" = $ThreadsafeHashtable} #> param ( # PowerShell Command or Script to run against each InputObject [Parameter(Mandatory = $true)] $Command, # Objects to pass to the Command as an argument or parameter [Parameter( ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] $InputObject, # Named parameter of the Command to pass InputObject to # If this is not specified, InputObject will be passed to the Command as an argument $InputParameter = $null, # Maximum number of concurrent threads to allow [int]$Threads = 20, # Milliseconds to wait between cycles of the loop that checks threads for completion [int]$SleepTimer = 200, # Seconds to wait without receiving any new results before giving up and stopping all remaining threads [int]$Timeout = 120, <# Parameters to add to the Command Each parameter is a name-value pair in the hashtable: @{"ParameterName" = "Value"} @{"ParameterName" = "Value" ; "ParameterTwo" = "Value2"} #> [HashTable]$AddParam = @{}, # Switches to add to the Command [string[]]$AddSwitch = @(), # Names of modules to import in each runspace [String[]]$AddModule, <# Name of a property (whose value is a string) that exists on each $InputObject and can be used to represent the object in text form If left null, the object's ToString() method will be used instead. #> [string]$ObjectStringProperty, # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) begin { $LogParams = @{ Type = $DebugOutputStream ThisHostname = $TodaysHostname } Write-LogMsg @LogParams -Text " # Entered begin block for '$Command'" Write-LogMsg @LogParams -Text " `$InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() # for '$Command'" $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() # Import the source module containing the specified Command in each thread $OriginalCommandInfo = Get-PsCommandInfo -Command $Command -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname Write-LogMsg @LogParams -Text " # Found 1 original PsCommandInfo for '$Command'" $CommandInfo = Expand-PsCommandInfo -PsCommandInfo $OriginalCommandInfo -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname Write-LogMsg @LogParams -Text " # Found $(($CommandInfo | Measure-Object).Count) nested PsCommandInfos for '$Command' ($($CommandInfo.CommandInfo.Name -join ','))" # Prepare our collection of PowerShell modules to import in each thread # This will include any modules specified by name with the -AddModule parameter $ModulesToAdd = [System.Collections.Generic.List[System.Management.Automation.PSModuleInfo]]::new() ForEach ($Module in $AddModule) { Write-LogMsg @LogParams -Text " Get-Module -Name '$Module'" $ModuleObj = Get-Module -Name $Module -ErrorAction SilentlyContinue $null = $ModulesToAdd.Add($ModuleObj) } # This will also include any modules identified by tokenizing the -Command parameter or its definition, and recursing through all nested command tokens $CommandInfo.ModuleInfo | Sort-Object -Property Name -Unique | ForEach-Object { $null = $ModulesToAdd.Add($_) } $CommandInfo = $CommandInfo | Where-Object -FilterScript { $ModulesToAdd.Name -notcontains $_.ModuleInfo.Name -and $_.CommandType -ne 'Cmdlet' } Write-LogMsg @LogParams -Text " # Found $(($CommandInfo | Measure-Object).Count) remaining PsCommandInfos to define for '$Command' (not in modules: $($CommandInfo.CommandInfo.Name -join ','))" if ($ModulesToAdd.Count -gt 0) { $null = Add-PsModule -InitialSessionState $InitialSessionState -ModuleInfo $ModulesToAdd -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname } # Set the preference variables for PowerShell output streams in each thread to match the current preferences $OutputStream = @('Debug', 'Verbose', 'Information', 'Warning', 'Error') ForEach ($ThisStream in $OutputStream) { if ($ThisStream -eq 'Error') { $VariableName = 'ErrorActionPreference' } else { $VariableName = "$($ThisStream)Preference" } $VariableValue = (Get-Variable -Name $VariableName).Value $VariableEntry = [System.Management.Automation.Runspaces.SessionStateVariableEntry]::new($VariableName, $VariableValue, '') $InitialSessionState.Variables.Add($VariableEntry) } Write-LogMsg @LogParams -Text " `$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $Threads, `$InitialSessionState, `$Host) # for '$Command'" $RunspacePool = [runspacefactory]::CreateRunspacePool(1, $Threads, $InitialSessionState, $Host) Write-LogMsg @LogParams -Text " `$RunspacePool.Open() # for '$Command'" $RunspacePool.Open() $Global:TimedOut = $false $AllInputObjects = [System.Collections.Generic.List[psobject]]::new() } process { if ($ObjectStringProperty) { $ObjectString = $InputObject.$ObjectStringProperty } else { $ObjectString = $InputObject.ToString() } Write-LogMsg @LogParams -Text " # Entered process block for '$Command' on '$ObjectString'" # Add all the input objects from the pipeline to a single collection; allows progress bars later ForEach ($ThisObject in $InputObject) { $null = $AllInputObjects.Add($ThisObject) } } end { Write-LogMsg @LogParams -Text " # Entered end block for '$Command'" Write-LogMsg @LogParams -Text " # Sending $(($CommandInfo | Measure-Object).Count) PsCommandInfos to Open-Thread for '$Command'" $ThreadParameters = @{ Command = $Command InputParameter = $InputParameter InputObject = $AllInputObjects AddParam = $AddParam AddSwitch = $AddSwitch ObjectStringProperty = $ObjectStringProperty CommandInfo = $CommandInfo RunspacePool = $RunspacePool DebugOutputStream = $DebugOutputStream } $AllThreads = Open-Thread @ThreadParameters Write-LogMsg @LogParams -Text " # Received $(($AllThreads | Measure-Object).Count) threads from Open-Thread for $Command" Wait-Thread -Thread $AllThreads -Threads $Threads -SleepTimer $SleepTimer -Timeout $Timeout -Dispose -DebugOutputStream $DebugOutputStream -TodaysHostname $TodaysHostname $VerbosePreference = 'Continue' if ($Global:TimedOut -eq $false) { Write-LogMsg @LogParams -Text " [System.Management.Automation.Runspaces.RunspacePool]::Close()" $null = $RunspacePool.Close() Write-LogMsg @LogParams -Text " [System.Management.Automation.Runspaces.RunspacePool]::Close() completed" Write-LogMsg @LogParams -Text " [System.Management.Automation.Runspaces.RunspacePool]::Dispose()" $null = $RunspacePool.Dispose() Write-LogMsg @LogParams -Text " [System.Management.Automation.Runspaces.RunspacePool]::Dispose() completed" } Write-Progress -Activity 'Completed' -Completed } } function Wait-Thread { <# .Synopsis Waits for a thread to be completed so the results can be returned, or for a timeout to be reached .Description Used by Split-Thread .INPUTS [PSCustomObject]$Thread .OUTPUTS Outputs the specified output streams from the threads #> param ( # Threads to wait for [Parameter( Mandatory = $true, ValueFromPipeline = $true )] [PSCustomObject[]]$Thread, # Maximum number of concurrent threads that are allowed (used only for progress display) [int]$Threads = 20, # Milliseconds to wait between cycles of the loop that checks threads for completion [int]$SleepTimer = 200, # Seconds to wait without receiving any new results before giving up and stopping all remaining threads [int]$Timeout = 120, # Dispose of the thread when it is finished [switch]$Dispose, # Will be sent to the Type parameter of Write-LogMsg in the PsLogMessage module [string]$DebugOutputStream = 'Silent', [string]$TodaysHostname = (HOSTNAME.EXE) ) begin { $StopWatch = [System.Diagnostics.Stopwatch]::new() $StopWatch.Start() $AllThreads = [System.Collections.Generic.List[PSCustomObject]]::new() $FirstThread = $Thread | Select-Object -First 1 $RunspacePool = $FirstThread.PowershellInterface.RunspacePool $CommandString = $FirstThread.Command $LogParams = @{ Type = $DebugOutputStream ThisHostname = $TodaysHostname } } process { ForEach ($ThisThread in $Thread) { # If the threads do not have handles, there is nothing to wait for, so output the thread as-is. # Otherwise wait for the handle to indicate completion (or a timeout to be reached) if ($ThisThread.Handle -eq $false) { Write-LogMsg @LogParams -Text " `$PowerShellInterface.Streams.ClearStreams() # for '$CommandString' on '$($ThisThread.ObjectString)'" $null = $ThisThread.PowerShellInterface.Streams.ClearStreams() $ThisThread } else { $null = $AllThreads.Add($ThisThread) } } } end { # If the threads have handles, we can check to see if they are complete. While (@($AllThreads | Where-Object -FilterScript { $null -ne $_.Handle }).Count -gt 0) { Write-LogMsg @LogParams -Text " Start-Sleep -Milliseconds `$SleepTimer # for '$CommandString'" Start-Sleep -Milliseconds $SleepTimer if ($RunspacePool) { $AvailableRunspaces = $RunspacePool.GetAvailableRunspaces() } $CleanedUpThreads = [System.Collections.Generic.List[PSCustomObject]]::new() $CompletedThreads = [System.Collections.Generic.List[PSCustomObject]]::new() $IncompleteThreads = [System.Collections.Generic.List[PSCustomObject]]::new() ForEach ($ThisThread in $AllThreads) { if ($null -eq $ThisThread.Handle) { $null = $CleanedUpThreads.Add($ThisThread) } if ($ThisThread.Handle.IsCompleted -eq $true) { $null = $CompletedThreads.Add($ThisThread) } if ($ThisThread.Handle.IsCompleted -eq $false) { $null = $IncompleteThreads.Add($ThisThread) } } $ActiveThreadCountString = "$($Threads - $AvailableRunspaces) of $Threads are active" Write-LogMsg @LogParams -Text " # $ActiveThreadCountString for '$CommandString'" Write-LogMsg @LogParams -Text " # $($CompletedThreads.Count) completed threads for '$CommandString'" Write-LogMsg @LogParams -Text " # $($CleanedUpThreads.Count) cleaned up threads for '$CommandString'" Write-LogMsg @LogParams -Text " # $($IncompleteThreads.Count) incomplete threads for '$CommandString'" $RemainingString = "$($IncompleteThreads.ObjectString)" If ($RemainingString.Length -gt 60) { $RemainingString = $RemainingString.Substring(0, 60) + "..." } $Progress = @{ Activity = "Waiting on threads - $ActiveThreadCountString`: $CommandString" PercentComplete = ($($CleanedUpThreads).count) / @($Thread).Count * 100 Status = "$(@($IncompleteThreads).Count) remaining - $RemainingString" } Write-Progress @Progress ForEach ($CompletedThread in $CompletedThreads) { # TODO: Debug these counts, something seems off, they vary wildly with Test-Multithreading.ps1 but I would expect consistency (same number of Warnings per thread) Write-LogMsg @LogParams -Text " # $($CompletedThread.PowerShellInterface.Streams.Progress.Count) Progress messages for '$CommandString' on '$($CompletedThread.ObjectString)'" Write-LogMsg @LogParams -Text " # $($CompletedThread.PowerShellInterface.Streams.Information.Count) Information messages for '$CommandString' on '$($CompletedThread.ObjectString)'" Write-LogMsg @LogParams -Text " # $($CompletedThread.PowerShellInterface.Streams.Verbose.Count) Verbose messages for '$CommandString' on '$($CompletedThread.ObjectString)'" Write-LogMsg @LogParams -Text " # $($CompletedThread.PowerShellInterface.Streams.Debug.Count) Debug messages for '$CommandString' on '$($CompletedThread.ObjectString)'" Write-LogMsg @LogParams -Text " # $($CompletedThread.PowerShellInterface.Streams.Warning.Count) Warning messages for '$CommandString' on '$($CompletedThread.ObjectString)'" # Because $Host was used to create the RunspacePool, any output to $Host (which includes Write-Host and Write-Information and Write-Progress) has already been displayed #$CompletedThread.PowerShellInterface.Streams.Progress | ForEach-Object {Write-Progress "$_"} #$CompletedThread.PowerShellInterface.Streams.Information | ForEach-Object { Write-Information "$_" } #$CompletedThread.PowerShellInterface.Streams.Verbose | ForEach-Object { Write-Verbose "$_" } #$CompletedThread.PowerShellInterface.Streams.Debug | ForEach-Object { Write-Debug "$_" } #$CompletedThread.PowerShellInterface.Streams.Warning | ForEach-Object { Write-Warning "$_" } Write-LogMsg @LogParams -Text " `$PowerShellInterface.Streams.ClearStreams() # for '$CommandString' on '$($CompletedThread.ObjectString)'" $null = $CompletedThread.PowerShellInterface.Streams.ClearStreams() Write-LogMsg @LogParams -Text " `$PowerShellInterface.EndInvoke(`$Handle) # for '$CommandString' on '$($CompletedThread.ObjectString)'" $ThreadOutput = $CompletedThread.PowerShellInterface.EndInvoke($CompletedThread.Handle) if ($Dispose -eq $true) { <#NormallyCommentThisForPerformanceOptimization#>## if (($ThreadOutput | Measure-Object).Count -gt 0) { <#NormallyCommentThisForPerformanceOptimization#>## Write-LogMsg @LogParams -Text " # Output (count of $($ThreadOutput.Count)) received from thread $($CompletedThread.Index): $($CompletedThread.ObjectString)" <#NormallyCommentThisForPerformanceOptimization#>## } <#NormallyCommentThisForPerformanceOptimization#>## else { <#NormallyCommentThisForPerformanceOptimization#>## Write-LogMsg @LogParams -Text " # Null result for thread $($CompletedThread.Index) ($($CompletedThread.ObjectString))" <#NormallyCommentThisForPerformanceOptimization#>## } $ThreadOutput Write-LogMsg @LogParams -Text " `$PowerShellInterface.Dispose() # for '$CommandString' on '$($CompletedThread.ObjectString)'" $null = $CompletedThread.PowerShellInterface.Dispose() $CompletedThread.PowerShellInterface = $null $CompletedThread.Handle = $null } else { Write-LogMsg @LogParams -Text " # Thread $($CompletedThread.Index) is finished opening for '$CommandString' on '$($CompletedThread.ObjectString)'" $CompletedThread.Handle = $null $CompletedThread } $StopWatch.Reset() $StopWatch.Start() } If ($StopWatch.ElapsedMilliseconds / 1000 -gt $Timeout) { Write-Warning " Reached Timeout of $Timeout seconds. Skipping $($IncompleteThreads.Count) remaining threads: $RemainingString" $Global:TimedOut = $true $IncompleteThreads | ForEach-Object { $_.Handle = $null [PSCustomObject]@{ Handle = $null PowerShellInterface = $_.PowershellInterface Object = $_.Object ObjectString = $_.ObjectString Index = $_.CurrentObjectIndex Command = $_.Command } } } } $StopWatch.Stop() Write-LogMsg @LogParams -Text " # Finished waiting for threads" Write-Progress -Activity 'Completed' -Completed } } <# # Dot source any functions ForEach ($ThisScript in $ScriptFiles) { # Dot source the function . $($ThisScript.FullName) } #> Import-Module PsLogMessage -ErrorAction SilentlyContinue Export-ModuleMember -Function @('Add-PsCommand','Add-PsModule','Convert-FromPsCommandInfoToString','Expand-PsCommandInfo','Expand-PsToken','Get-PsCommandInfo','Open-Thread','Split-Thread','Wait-Thread') |