Comparing array variables in PowerShell

In PowerShell, variables that point to arrays are evaluated in expressions by enumerating the contents of the arrays themselves. For example this expression: $firstFolder | Get-Member will return information about the System.IO.DirectoryInfo type, which indeed is the type of the first element in the $firstFolder array. If you want to operate on the array object … Read more

PowerShell – How to Import-Module in a Runspace

There are two ways to import modules programmatically, but I’ll address your method first. Your line pipeline.Commands.Add(“…”) should only be adding the command, not the command AND the parameter. The parameter is added separately: # argument is a positional parameter pipeline.Commands.Add(“Import-Module”); var command = pipeline.Commands[0]; command.Parameters.Add(“Name”, @”G:\PowerShell\PowerDbg.psm1″) The above pipeline API is a bit clumsy … Read more

How to export data to CSV in PowerShell?

This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV. $results = @() foreach ($computer in $computerlist) { if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet)) { foreach ($file in $REMOVE) { Remove-Item “\\$computer\$DESTINATION\$file” -Recurse Copy-Item E:\Code\powershell\shortcuts\* … Read more

How do I include a locally defined function when using PowerShell’s Invoke-Command for remoting?

You need to pass the function itself (not a call to the function in the ScriptBlock). I had the same need just last week and found this SO discussion So your code will become: Invoke-Command -ScriptBlock ${function:foo} -argumentlist “Bye!” -ComputerName someserver.example.com -Credential [email protected] Note that by using this method, you can only pass parameters into … Read more

How to keep the shell window open after running a PowerShell script?

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post. One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit “C:\SomeFolder\SomeScript.ps1” Per-script Fix: Add a prompt for input to the end … Read more

How do I concatenate two text files in PowerShell?

Simply use the Get-Content and Set-Content cmdlets: Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt You can concatenate more than two files with this style, too. If the source files are named similarly, you can use wildcards: Get-Content inputFile*.txt | Set-Content joinedFile.txt Note 1: PowerShell 5 and older versions allowed this to be done more concisely using … Read more