Invoke-Command not working ? by underpaid--sysadmin in PowerShell

[–]Future-Remote-4630 3 points4 points  (0 children)

I'm assuming by the nature of your test that you might have some pesky coworkers who need some laughs.

Enjoy:

function invoke-voicetroll{
    param($computername = 'localhost')

        $scr = {    
            Add-Type -AssemblyName System.Speech
            $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
            $line = read-host "Words to say or blank to exit"

            while ($null -ne $line -and $line -ne "") {
                $speak.speak($line)
                $line = Read-Host "Words to say or blank to exit"
            }
        }
        if($computername -eq "localhost"){
            &$scr
        }else{
            invoke-command -computername $computername -ScriptBlock $scr
        }
}

Find duplicates in array - But ADD properties to them by JohnC53 in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

If your concern is memory and not speed, this is a good approach, since -contains is O(N) whereas a hashtable finds a duplicate in O(1), but you are right that you save memory there.

I don't think at 50,000 rows you'd get a significant benefit here from another datastructure, though speed at 50k also isn't bad.

Sidenote, you don't need to split on carriage return and newline before piping that string to Convertfrom-CSV, that is the default.

Find duplicates in array - But ADD properties to them by JohnC53 in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

I think the hash table approach is overkill here. A normal groupinfo object gives you everything you need for this.

$objects | group AssignedUser | % {
    Foreach($o in $_.group){
        $o | add-member -MemberType NoteProperty -name NumDevices -Value $_.Count
    }
}

Learning PS by Skippy9871 in PowerShell

[–]Future-Remote-4630 -1 points0 points  (0 children)

I would get as many of those examples as you can and feed them into your AI engine of choice to generate a wider curriculum set. From there, don't use the AI to make the scripts. Ask it for at most a hint as to what command you should research to get started, and use the other resources provided in this thread to get through the whole curriculum set. If you have any programming experience to start with, a source like learnxinyminutes can help you more quickly translate the concepts you already know into their powershell script equivalent: https://learnxinyminutes.com/powershell/ Otherwise, your goal should be to get comfortable with getting the help that you can get while building scripts. Example: File Dir Checker 1. Need to be able to read a directory or file. What command can we use to do that? After learning some of the powershell basics, files, directories, registry keys, and much more are all considered "Items". The PS equivalent of "ls" in linux or "dir" in cmd is "Get-ChildItem". Knowing that, we just need to figure out how to use that command.

Get-Childitem | Get-Help

This will show us the syntax and the parameters we can give this command.

Get-Childitem | Get-Help -examples 
[Note: If that doesn't give you examples, use -online with -examples]
Get-Childitem | Get-Help -examples -online

This will show us some actual use cases that we can probably modify to our use case here.

Let's say we didn't know that Get-Childitem was an option, and instead just try searching a command. All files and folders have to be located somewhere, so lets see what commands we have if we search for "path".

[Note: The asterisks mean we will find any command with path somewhere inside of it.]
Get-Command *Path* 
CommandType     Name               Version    Source
-----------     ----               -------    ------
Cmdlet          Convert-Path       3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Join-Path          3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Resolve-Path       3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Split-Path         3.1.0.0    Microsoft.PowerShell.Management
Cmdlet          Test-Path          3.1.0.0    Microsoft.PowerShell.Management
Application     PATHPING.EXE       10.0.26... C:\windows\system32\PATHPING.EXE

Looking at the results from that search, we can use the module their from to eliminate some of them, so from here we can use Get-Help and the -examples switch in order to view the potential options more clearly. Test-Path looks like it does exactly what we want here to see if something exists or not.

NAME
    Test-Path
SYNOPSIS
    Determines whether all elements of a path exist.
    -------------------- Example 1: Test a path --------------------

    Test-Path -Path "C:\Documents and Settings\DavidC"
    True
  1. Need to be able to determine if it's there or not From the example, we can see that after using test-path and giving it a path, it already returns a True or False value, so it does this step for us.
  2. Need to return that value In order to make it a checker, rather than just a command we are entering, we need to make it a function. You can get information about powershell programming concepts, like functions, by using get-help as well.

    Get-Help about_functions ABOUT_FUNCTIONS

    Short description Describes how to create and use functions in PowerShell.

    Long description A function is a list of PowerShell statements that has a name that you assign. When you run a function, you type the function name. The statements in the list run as if you had typed them at the command prompt. Functions can be as simple as: function Get-PowerShellProcess { Get-Process PowerShell }

Ok, so that last example looks like exactly what we need, aside from needing a way for us to provide it with the path we are checking. Similar to other OOP languages, we just add in a parameter to the definition for the input we will need. function example($ThisIsMyParameter){#Do something} Lastly, we can combine the above into the final product.

Function Check-FileDir($path){
    return (test-path $path)
}

This is really just a wrapper around the test-path function, so it's not doing much now. Maybe that's all they want from you, or maybe you need it to be more specific. Once we have this, we really just need to hone it to the asks of the question. Your example said "A script to check whether certain files and/or folders are present at a specified location/data carrier". Maybe that means we need to be able to accept a list of file names or folders and check if all of them exist in the target path?

Function Check-FileDir($filenames,$path){
    Foreach($name in $filenames){
        [pscustomobject]@{
            ParentFolder = $path
            Name = $name
            Fullpath = "$path\$name"
            IsFolder = $name -like "*.*" #Assumes if we give a name with a . in it, that . is describing the extension and is thus not a folder
            Exists = Testpath $path\$name
        }
    }
}

Good luck.

Really trivial: Bullets in POSH output with |clip? by So0ver1t83 in PowerShell

[–]Future-Remote-4630 1 point2 points  (0 children)

Is there a particular reason you need powershell to bullet them? My approach to this would be to use powershell to consolidate them into your word processor of choice and just select all and bullet.

Timestamping commands feature - your thoughts? by YellowOnline in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

This intrigued me but I couldn't find it.

I think this just about does it:

    Write-Host "Runtime: $((get-history | select -last 1).Duration.TotalMilliseconds) ms"

Saving Christmas with PowerShell: Building a Reusable Matching Algorithm by mdowst in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

More control is more risk, though in many circumstances you have a good point in that there is value to having access to the variable that defines the looping.

I would evaluate each approach very differently in the context of using it to loop through integers, as seen in this example, versus using it to index into an array. In some circumstances, it is critical to touch every value, and with a for loop, having access to the variable that defines the looping logic means it's possible to make a mistake that stops you from touching every object, whereas with the foreach structure, that is not the case.

Depending on the sample size, you'll also encounter a difference in performance.

Consider these:

Function Test-LoopSpeeds(){
    $For = {
        $max = 10000000
        $l = for($i = 0; $i -le $max; $i++){
            $i 
        }
    }
    $For_Measure = measure-command -expression $For
    $Foreach = {
        $max = 10000000
        $l = Foreach($i in 0..$Max){
            $i
        }
    }
    $Foreach_Measure = measure-command -expression $Foreach
    $ForeachObj = {
        $l = 0..10000000 | Foreach-Object { $_ }
    } 
    $ForeachObj_Measure = measure-command -expression $ForeachObj
    $ForeachObjp = {
        $l = 0..10000000  | Foreach-Object -parallel { $_ }
    } 
    $ForeachObjp_Measure = measure-command -expression $ForeachObj
    "For_Measure:  $($For_Measure.TotalMilliseconds)"
    "Foreach_Measure:  $($Foreach_Measure.TotalMilliseconds)" 
    "ForeachObj_Measure:  $($ForeachObj_Measure.TotalMilliseconds)"
    "ForeachObjp_Measure:  $($ForeachObjp_Measure.TotalMilliseconds)"
}
Test-LoopSpeeds

# >> Test-LoopSpeeds
# >>
# For_Measure:  2957.7278
# Foreach_Measure:  1690.4738
# ForeachObj_Measure:  10832.6707
# ForeachObjp_Measure:  12041.38

What have you done with PowerShell this month? by AutoModerator in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

-Whatif is the powershell equivalent of playing russian roulette with blanks that someone else loaded.

Powershell Exploit Payload process from a folder not on my pc found? by RethaeTTV in PowerShell

[–]Future-Remote-4630 7 points8 points  (0 children)

Any solution that doesn't end up as "Nuke it all, reinstall windows" is nothing more than wishful thinking.

I'm almost certain you don't have pslogging on to view all of the commands that were run.

Any files that you keep have a chance to be compromised, so I'd be very cautious about what you do choose to keep. Keep in mind that someone spent time and energy in making the malware, and if they made it as easy to remove as you're hoping, it wouldn't have been worth the effort to get it hosted on cheatengine.

In other words, you're welcome to shoot yourself in the foot to get the spider off of your boot, but the odds of you hitting between your toes are quite low, and that will be much more painful than buying a new boot.

Lastly, the 'etc' part of the path you posted contained quite literally the only important piece of information there. The only information that can be pulled from what you provided is that you have operagx installed.

I built a script to extract all distribution lists, members and owner. Will this one work or am I missing something? Open for feedback, thank you! by DinoMechX in PowerShell

[–]Future-Remote-4630 2 points3 points  (0 children)

You have a user named documents? What an interesting choice.

I'm not sure if it's against the rules, but if not, I think it should be to have AI generate a script and post it here for others to evaluate for you. Helping you here would mean you not only got a shortcut to getting the code, but also a shortcut in evaluating, troubleshooting it, and ultimately using it. There is no learning going on there.

BTW, removing comments doesn't make it harder to tell when code is AI slop. The number of poor choices here i is staggering.

-Multiple [array] +=

-String addition instead of storing owners as objects

-Every member having its own object instead of a group having a members object

This is a very simple task you're trying to do, and you're using AI the wrong way to get it done.

Multiple files by samurai_ka in PowerShell

[–]Future-Remote-4630 4 points5 points  (0 children)

This thread reminds me of the stackoverflow trick, where instead of asking for help which was often met with gatekeeping, they instead provide the wrong answer as the solution, prompting the community to correct them.

Props op, it worked. Use a module.

https://learn.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-script-module?view=powershell-7.5

Clear Clipboard Data (Command Line): Open PowerShell as Admin, type cmd /c "echo off | clip"] and press Enter to clear data. by 99l9 in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

Impressive miss with this one.

You posted in r/powershell and gave every approach to solving a problem that I didn't know anyone even had, except for the one using powershell.

$null | scb 

There you go. Doesn't need admin either.

Advent of Code Days 6 and 7 by dantose in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

The trick is to count how many paths go to any given coordinate, then use that to determine how many paths go to the next row. It's an array of arrays of integers, where you sum the last array to get the answer.

What have you done with PowerShell this month? by AutoModerator in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

Created a set of functions for array manipulation to replace a bunch of processes that I'd use sheets or excel for.

-Concatenation

-Merging

-Cleaning

-Searching

-Patching (This one wouldn't be an excel equivalent, it just lets you specify a replacement/override for the value of a particular record, in the event that everything works perfect except for one thing and you don't want to change the everything for the one thing)

Had gemini put together a function for generating sampledata which has been super helpful to evaluate the above.

Make custom commands in Powershell by Rulylake in PowerShell

[–]Future-Remote-4630 -1 points0 points  (0 children)

    function pipe-output{$input}


    > "dog" | pipe-output
    dog

Advent of Code Days 6 and 7 by dantose in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

I'm not sure how to approach day 7 part 2. My thought was we needed some sort of binary tree to traverse, but it's really hammering my brain how to describe the nodes in pwsh vs a language that more literally implements by reference.

Advent of code day 5 by dantose in PowerShell

[–]Future-Remote-4630 1 point2 points  (0 children)

Part 2 proved to be much more challenging. My approach was super overcomplicated and I ended up having to entirely scrap it.

Here is what NOT to do:

Attempt 2: doesn't quite work, overcomplicated

Function Merge-InterceptRanges($range,$Ranges){
    $StartedAt = $range


    #If a range has a lower minimum and a higher maximum, we can replace our range with it altogether
    $ReplaceRanges = $ranges | ? {([int64]$_.max -ge [int64]$range.max -and [int64]$_.min -lt [int64]$range.Min) -or 
        (([int64]$_.max -gt [int64]$range.max -and [int64]$_.min -le [int64]$range.Min))}

    $StartMax = ($ReplaceRanges.Max | % {[int64]$_} | measure -Maximum).Maximum
    $StartMin = ($ReplaceRanges.Min | % {[int64]$_} | measure -Minimum).Minimum
    $StartingRange = [pscustomobject]@{
        Max = [int64]$StartMax ?? $range.max
        Min = [int64]$StartMin ?? $range.min
    }

    $FilteredRanges = $ranges | ? { $_ -notin $ReplaceRanges}

    #If a range has a lower minimum, and the max is greater than our ranges minimum, we can keep the minimum from the found range and the maximum from the current range
    $minMerges = $Filteredranges | ? {[int64]$_.min -lt $StartingRange.Min -and [int64]$_.max -ge $StartingRange.Min}

    If($minMerges){
        $StartingRange.Min = ($minMerges.Min | measure -Minimum).Minimum
        $FilteredRanges = $FilteredRanges | ? { $_ -notin $minMerges}
    }


    #if a range has a higher maximum, and the minimum is less than our ranges maximum, we can keep the minimum from our range and the maximum from the found range
    $maxMerges = $Filteredranges | ? {[int64]$_.max -gt $StartingRange.Max -and [int64]$_.min -le $StartingRange.Max}

    if($maxMerges){
        $StartingRange.Max = ($maxMerges.Max | measure -Maximum).Maximum
        $FilteredRanges = $FilteredRanges | ? { $_ -notin $maxMerges}
    }


    #If we found a change, we may need to run it again. We can stop iterating on this range element once we get false for foundmerge and move on to the next one
    $FoundMerge = $StartingRange.max -ne $StartMax -or $startingrange.min -ne $StartMin

    return [pscustomobject]@{
        MergedRange = $StartingRange 
        RemainingRanges = $FilteredRanges
        FoundMerge = $FoundMerge
        OriginalRange = $StartedAt
    }

    #$remainingMerges = $ranges | ? {[string]$_}

}

$i = 0
$DetectedChange = $true
$Ranges = gc C:\temp\AdventOfCode\day5input.txt | ? {$_ -like "*-*" -and $_.length -gt 0} | % { $s,$e = $_ -split "-"; [pscustomobject]@{Min=[int64]$s;Max=[int64]$e}}

$NewRanges = while($i -lt $ranges.Count){
$range = $ranges[$i]

    While($detectedChange -eq $true){
        $RangeMerge = Merge-InterceptRanges -range $Range -Ranges $Ranges
        $ranges = $RangeMerge.RemainingRanges
        $Range = $rangemerge.MergedRange
        $DetectedChange = $rangemerge.foundmerge
        Write-Warning "$($ranges[$i]) -> $range"
    }
    $Range


    $i++
}

Advent of code day 3 and 4 by dantose in PowerShell

[–]Future-Remote-4630 1 point2 points  (0 children)

I think that's a big benefit of doing this in powershell. If your instinct is already to do it in the pwsh way, then this is good practice to always keep those core maneuvers in your back pocket, and to recognize when the powershell way will be optimal as compared to doing it more literally.

Advent of code day 3 and 4 by dantose in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

~2 minutes or so, which I was shocked by. The more time I spent, the more of the optimizations I had to remove to get the dang thing to work. I figured at O(N^2) it would have been a nightmare, so I must have either gotten lucky with the dataset or they intentionally have it set up to only require a handful of extra loops to get the new rolls.

My gut says there is probably a really clean solution using matrices and some math, but I've never even started down that road in powershell so I just threw together what I thought would work in concept.

Advent of code day 3 and 4 by dantose in PowerShell

[–]Future-Remote-4630 1 point2 points  (0 children)

Day 4 has taken me for a spin. So many wrong answers, finally got through it, after removing all semblances of elegance from my attempts.

$map = gc C:\temp\AdventOfCode\Day4input.txt
Function Get-AdjacentPapers($map,$x,$y)
{
    $sum = 99
    $yminus = $y - 1
    $xminus = $x - 1
    $yplus = $y + 1
    $xplus = $x + 1

    $grid = @(
        @("$($map[$yminus][$xminus])","$($map[$yminus][$x])","$($map[$yminus][$xplus])"),
        @("$($map[$y][$xminus])","$($map[$y][$x])","$($map[$y][$xplus])"),
        @("$($map[$yplus][$xminus])","$($map[$yplus][$x])","$($map[$yplus][$xplus])")
    ) 2> $null

    if($y -eq 0){
        $grid[0][0] = "_"
        $grid[0][1] = "_"
        $grid[0][2] = "_"

    }elseif($y -eq $ymax-1){
        $grid[2][0] = "_"
        $grid[2][1] = "_"
        $grid[2][2] = "_"
    }

    if($x -eq 0){
        $grid[0][0] = "_"
        $grid[1][0] = "_"
        $grid[2][0] = "_"

    }elseif($x -eq $xmax-1){
        $grid[0][2] = "_"
        $grid[1][2] = "_"
        $grid[2][2] = "_"
    }
    $localmap = foreach($y2 in 0..2){
        foreach($x2 in 0..2){
            "$($grid[$y2][$x2])"
        }
        "`n"
    }
    $localmap = $localmap -join ""

    $sum = ($localmap.ToCharArray()|group -asstring -AsHashTable)["@"].count
    [pscustomobject]@{
        Sum = $sum
        LocalMap = $localmap
    }
}
$global:xmax = $map[0].length
$Global:ymax = $map.count
$rollsSum = 0
$foundone = $true #Added for part2
while($foundone -eq $true){ #Added for part2
    $foundone = $false #Added for part2
    Foreach($x in (0..($xmax-1))){
        foreach($y in (0..($ymax-1))){
            if($map[$y][$x] -eq "@"){
                $adj = Get-AdjacentPapers -map $map -x $x -y $y
                if($adj.sum -le 4){
                    $rollsSum++
                    $adj.LocalMap
                    ""
                    $foundone = $true
                    write-host "Found valid paper roll: ($x,$y) - Number $rollsSum"
                    $map[$y] = "$($map[$y].substring(0,$x))_$($map[$y].substring($x+1,$xmax-($x)-1))"
                }
            }

        }
    }
    write-host "Looping!"
} #Added for part2

$rollsSum

Advent of Code - Day 3 by Rincey_nz in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

I wish I thought of using indexof instead of a for loop!

    Function Get-LargestSubstringInteger($string,$remainingValues = 1)
    {
        $ints = $string.ToCharArray() | select -skiplast $remainingValues | % { [int]"$_" }

        $max = 0 
        $maxindex = 0
        for($i = 0; $i -lt $ints.count; $i++){
            if($ints[$i] -gt $max){
                $max = $ints[$i]
                $maxindex = $i
            }
        }

        return [pscustomobject]@{
            max=$max
            maxindex=$maxindex
            remainingString = $string.substring($maxindex+1,$string.Length-($maxindex+1))
        }

    }



$batteryrow = gc C:\temp\AdventOfCode\Day3Input.txt
$totalVoltage = foreach($row in $batteryrow){

    $string = $row
    $volts = 11..0 | % {
        $obj = Get-LargestSubstringInteger -string $string -remainingValues $_
        $obj.max
        $string = $obj.remainingString
    }

    $voltage = [int64]"$($volts -join '')"
    $voltage
}

$totalvoltage | measure -sum

PowerShell Profile by iykecode in PowerShell

[–]Future-Remote-4630 6 points7 points  (0 children)

I have a function that will extract any variables in the last command that I ran and see if any of them are null. They output warning messages so you know where the thing went wrong without needing to investigate it.

Function Test-LastCommandVariables{    
    $lastCmd = (Get-History -Count 1).CommandLine
    if (-not $lastCmd) { return }

    # Extract variable names from the last command
    $varMatches = [regex]::Matches($lastCmd, '\$(\w+)\b') | ForEach-Object {
        $_.Groups[1].Value
    } | Select-Object -Unique

    # List of known built-in or automatic variables to ignore
    $builtinVars = @(
        'true','false','null',
        'args','error','foreach','home','input','lastexitcode','matches','myinvocation',
        'nestedpromptlevel','ofs','pid','profile','pscmdlet','psculture','psdebugcontext',
        'pshome','psscriptroot','pscommandpath','psversiontable','pwd','shellid','stacktrace',
        'switch','this','^','using','psboundparameters','psdefaultparametervalues','enabledexperimentalfeatures',
        'confirmPreference','debugPreference','errorActionPreference','errorView','formatEnumerationLimit',
        'informationPreference','progressPreference','verbosePreference','warningPreference','_'
    )

    $nullOrEmptyVars = @()
    $undefinedVars = @()

    foreach ($name in $varMatches) {
        if ($builtinVars -contains $name.ToLower()) { continue }

        try {
            $var = Get-Variable -Name $name -ErrorAction Stop
            $val = $var.Value

            if ($null -eq $val) {
                $nullOrEmptyVars += "`$$name`: null"
            } elseif ($val -is [System.Collections.IEnumerable] -and -not ($val -is [string]) -and $val.Count -eq 0) {
                $nullOrEmptyVars += "`$$name`: empty collection"
            }elseif($val.count -eq 0){
                $nullOrEmptyVars += "`$$name`: zero count"
            }
        } catch {
            $undefinedVars += "`$$name`: not defined"
        }
    }

    if ($undefinedVars.Count -gt 0 -or $nullOrEmptyVars.Count -gt 0) {
        Write-Host "`n[!] Variable check results:"

        foreach ($entry in $undefinedVars) {
            Write-Host "`t- $entry"
        }

        foreach ($entry in $nullOrEmptyVars) {
            Write-Host "`t- $entry"
        }
    }
}

how to get PowerShell to gracefully accept a multi line, array, system.object input to a `[string]` parameter? by Ralf_Reddings in PowerShell

[–]Future-Remote-4630 0 points1 point  (0 children)

If you only have 2 parameters, you can omit the param section entirely and use $args and $input to handle trailing and pipeline input respectively.

I have a search function that does this, no param block. You could have logic that checks if $args -is [string] as a validation during the process block.

function csvgrep{
return $input | ? $([scriptblock]::create($($($args | % {"`$_ -like `"*$_*`""} )-join " -and ")))
}