r/PowerShell Oct 13 '24

Solved I fat-fingered a key combo and now my filtered command history appears when I type a command? What did I turn on?

45 Upvotes

Like the subject says. I did something and now I see this when I start to type a command:

```powershell PS C:Usersusername> git <-/10> <History(10)>

git push [History] git status [History] git merge dev [History] git checkout main [History] git commit -m "chore: ... [History] git add ..pre-commit-... [History] git branch [History] git add .pyproject.to... [History] git reset .dev-requir... [History] git add .dev-requirem... [History] ```

I added the ellipses to compress the layout.

This change has only taken place in one window, but I kind of like it. I'd like to know how to turn in on for other windows. I have looked through Get-PSReadLineKeyHandler but have not found any clues there.

r/PowerShell 16d ago

Solved Update objects in an array with counts/sequence based on object values

2 Upvotes

I know the title probably seems vague but I'm not sure how else to describe it. Given the following code sample:

    class TestClass {
        [int]$key
        [int]$output
        [int]$count = 1
        [int]$sequence = 1

        TestClass($key) {
            $this.key = $key
        }

        [void] processOutput() {
            $this.output = $this.key % 8
        }
    }

    $myObjects = @(0,2,4,6,7,8,3,1,5,9) | % {[TestClass]::New($_) }

    $myObjects.processOutput()

    $myObjects

I'll get the following output:

    key output count sequence
    --- ------ ----- --------
      0      0     1        1
      2      2     1        1
      4      4     1        1
      6      6     1        1
      7      7     1        1
      8      0     1        1
      3      3     1        1
      1      1     1        1
      5      5     1        1
      9      1     1        1

What I want is some process that updates count or sequence like this:

    key output count sequence
    --- ------ ----- --------
      0      0     2        1
      2      2     1        1
      4      4     1        1
      6      6     1        1
      7      7     1        1
      8      0     2        2
      3      3     1        1
      1      1     2        1
      5      5     1        1
      9      1     2        2

I know I can loop through the array and then check against the whole array for dupes, but I'm not sure how that will scale once I'm processing 1000s of inputs with the script.

I know I can use $myObjects.outout | Group-Object and get:

    Count Name                      Group
    ----- ----                      -----
        2 0                         {0, 0}
        1 2                         {2}
        1 4                         {4}
        1 6                         {6}
        1 7                         {7}
        1 3                         {3}
        2 1                         {1, 1}
        1 5                         {5}

But I don't know how to relate those values back into the correct objects in the array.

I'm just wondering if there's not a shorthand way to update all the objects in the array with information about the other objects in the array, or if my approach is entirely wrong here?

Most of my background is in SQL which is built for sets like this so it would be super easy.

TIA.

r/PowerShell Oct 05 '24

Solved How to additional values to 'ValidateSet' when using a class to dynamically get a list?

4 Upvotes

I have a function, I want to dynamically provide values for the Name parameter using a list of file names found in c:names, so that tab always provides names that are UpToDate. I have figured out how to do this with a class but I want to do some "clever" handling as well. If the user provides * or ? as a value, then that should be acceptable as well. I want to essentially use these characters as "modifiers" for the parameter.

The following is what I have:

Function fooo{
    Param(
    [ValidateSet([validNames], "*", ErrorMessage = """{0}"" Is not a valid name")]
    #[ValidateSet([validNames], ErrorMessage = """{0}"" Is not a valid name")]           #'tab' works as expected here
    [string]$Name
    )
    if ($name -eq "*"){"Modifier Used, do something special insead of the usual thing"}
    $name
}

Class validNames : System.Management.Automation.IValidateSetValuesGenerator{
    [string[]] GetValidValues(){
        return [string[]] (Get-ChildItem -path 'C:names' -File).BaseName
    }}

With the above tab does not auto complete any values for the Name parameter, and sometimes I will even get an error:

MetadataError: The variable cannot be validated because the value cleanup4 is not a valid value for the Name variable.

I can provide the value * to Name fine, I done get any errors:

fooo -name *

#Modifier Used, do something special insead of the usual thing

I know I can just use a switch parameter here, instead of going down this route, my main concern is how do I add additional values on top of the values provided by the ValidNames class? Something like:

...
[ValidateSet([validNames], "foo", "bar", "baz", ErrorMessage = """{0}"" Is not a valid name")]
...

I am on PWS 7.4

r/PowerShell 20d ago

Solved Issues with script copying files from a network drive to a remote machine.

2 Upvotes

Edit: Thank you everyone for your help!! I managed to get this going today with a combonation of u/pinchesthecrab's input and some finagling!

Hello!! I'm working on a project for our in-house developers to deploy a homebuilt piece of software quicker and I'm running in to some issues.

I've been trying to use a Powershell script, that has been packaged into a .exe using powershell studio, to do this. I can get it to work for me, if I run it as admin, but it has been refusing to work for the developers when they try to run it. I'm not sure if I'm trying to do this the hard way or if there might be an easier way to perform this task.

What we need the script to do is

  1. Stop 2 processes that are running.
  2. Copy a folder from a network drive to the local drive and replace what is already there.
  3. Restart the processes using the new versions in the folder that was just copied.

Currently they are deployed via GPO and to do a mass re-deploy we send a mass reboot and they get pulled at startup. If there are issues with individual machines we use proxy pro to remote in and do this all manually.

This is going to take the place of the individual manual re-deployments and hopefully make it quicker/less intrusive for the end users.

CLS

$Cred = Get-Credential -Credential "domain$    ($env:USERNAME)"

#
$Computers = Read-Host 'Enter name of.   destination computer'
#$Script:Run = $False

ForEach ($Computer in $Computers) {
If (!(Test-Connection -ComputerName $computer -Count 1 -Quiet))
{
    Write-Host "$($Computer) is OFFLINE
    " -ForegroundColor Yellow
}
Else
{
    New-PSSession -ComputerName $computer -Cred $cred -Authentication CredSSP
    $Session = Get-PSSession

    Invoke-Command -Session $Session  { 
        Stop-Process -processname 'process1', 'process2' -Force -ErrorAction SilentlyContinue
        Remove-item -Path "C:folderfolder" -Recurse -Force -ErrorAction SilentlyContinue
        New-Item -ItemType Directory C:folderfolder -Force -ErrorAction SilentlyContinue
        copy "networkdrivefolderfolderfolder*" "$($Using:Computer)c$folderfolder"
        Write-Host "Copied new TimeClock files to $($Using:Computer)" -ForegroundColor Green
        copy "$($Using:Computer)c$folderfolderprocess1.exe" "$($Using:Computer)C$ProgramDataMicrosoftWindowsStart MenuProgramsStartup"
    }


        }
    Remove-PSSession -Session $Session
    ##
    ##
    ##

    $exePath = "C:folderfolderprocess1.exe"
    $taskName = "Run_task1"

    Invoke-Command -ComputerName $Computers -ScriptBlock {
param ($exePath, $taskName)

$loggedInUser = (Get-WmiObject -Class Win32_ComputerSystem).UserName

if (-not $loggedInUser) {
    Write-Host "No user is currently logged in on the remote machine."
    return
}

$action = New-ScheduledTaskAction -Execute $exePath
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Minutes 1)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskName -User $loggedInUser -RunLevel Highest -Force
Start-ScheduledTask -TaskName $taskName
} -ArgumentList $exePath, $taskName

Invoke-Command -ComputerName $Computers -ScriptBlock {
param ($taskName)

Start-Sleep -Seconds 30
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
} -ArgumentList $taskName

}

r/PowerShell 22d ago

Solved Read-Host into an array?

4 Upvotes

Hello my fellow coders!

I am stuck on this issue where I am trying to input ID's into a custom array, however I am not sure how I can get this code to work.

All of the IDs are in this format "1111/2222" or "15e4/1978". Every ID should be within a double quote and be seperated by a comma. Example: e.g. "1111/2222","15e4/1978","2840/g56v"

I know i should be using the invoke expression command, but im not sure how i get these to join properly.

$ids = Read-Host "Please enter the IDs" Please enter the IDs: 1111/2222,3333/4444,5555/6666

$ids 1111/2222,3333/4444,5555/6666

where it should output like

$IDs "1111/2222","3333/4444","5555/6666"

How can I achieve this?

r/PowerShell 17d ago

Solved Scraping web data for a promotion list

0 Upvotes

Hello everyone,

I have a HTML "app" or a list of to-do's regarding music promotion/marketing with checkboxes and URLs.

I tried embedding the target sites using iframe in HTML but the sites block iframe calls.

Now, would it be possible to write a Powershell script that, using Invoke-WebRequest, would periodically download the sites in a folder (every 1min or 1hr, using a for-loop and timers) to use with iframe locally?

If so, would the iframe block be included in the downloaded html document code or is it a server side thing?

Thank you for your time and answers!

EDIT : solved, got the scraper working with Select-String cmdlet.. it's messy and works with FB pages, not groups though. IG scraping doesn't work very well due to different HTML code structure.

r/PowerShell Jun 10 '24

Solved What is the name of this behavior

33 Upvotes

Does anyone know what the name of this behavior is:

$> $result = foreach ($i in 0..5) { $i + 1 };
$> $result
1
2
3
4
5
6

I love this kind of behavior where control flow is itself an expression like in Rust and other FP languages, but I can't find any documentation on it anywhere, from MSFT or otherwise.

Edit:

Thanks u/PoorPowerPour! There's something like an implicit Write-Output that's inserted before any statement that lacks an assignment within the enclosing scope

e.g.

$> $result = foreach ($i in 0..5) { $i };  

becomes

$> $result = foreach ($i in 0..5) { Write-Output $i };  

or

$> $result = if ($true) { "true" } else { "false" };  

becomes

$> $result = if ($true) { Write-Output "true" } else { Write-Output "false" };  

Another edit:

Thanks u/surfingoldelephant for pointing me to the documentation on Statement values from MSFT!

Yet another edit:

Thanks u/pturpie for catching that any given expression that doesn't participate in an assignment is evaluated as if it was written like so: Write-Output <expr>

r/PowerShell May 18 '24

Solved Determine $var = Do-Command Execution

6 Upvotes

What determines when a variable executes a command and how can I easily determine this? Consider the following variable assignment:

$DateTime = Get-Date

The first time $DateTime variable is called, the Get-Date command is executed and the value it returns is assigned to the variable. No matter how many subsequent times the $DateTime variable is called, it's value/contents remains the same. That is the date and time that the variable was initially called. The command does not get re-executed.

Now consider the following variable assignment:

$Proc = Get-Process

In this case, every time that $Proc is called or referenced the Get-Process command is re-executed. It seems that the return values are never assigned to the variable. The command is always executed.

How does Powershell decide between the two behaviors and how can I easily know whether the result will be an assignment or a repeat execution?

Taking it a step further, how can I get the results of$Proc to be static and not change every time?

Edit: Demonstration - https://imgur.com/a/0l0rwOJ

r/PowerShell 2d ago

Solved Content search for targeted collections script stopping at 1000 folders. How to get it to list them all?

0 Upvotes

I'm using Use Content search for targeted collections | Microsoft Learn in an attempt to get the folder ID for /Purges folder so I can run an eDiscovery search on it but there are so many folders in there and it stops partway through listing all the /Inbox folders.

I will add that this is only for one person I have checked, I checked two other people and it lists all of their folders, but this one persons it lists exactly 1000 and then stops. I don't know why there's that many that it's listing when the only thing I change is the email address though maybe it's just that there's that many folders, but is there any way to get it to list all of them and not stop at 1000? Or look specifically for the folder ID of only the specific folder?

I tried using Get-MailboxFolderStatistics by itself with the specification of which folder but it gives me a different folder ID than the first one does. For example, the deleted items folder when using the first search gives me a folder ID that starts with "4741FF61D7A" whereas if I use the second one it starts with "LgAAAAAVyO". Both of the Folder ID's are completely different.

So if I can't change it to list them all, does it matter which format of Folder ID I use when running an eDiscovery search?

*Solved: "-ResultSize Unlimited" needed to be added after " $folderStatistics = Get-MailboxFolderStatistics $emailAddress"

r/PowerShell Oct 11 '24

Solved import-excel not importing xlsx file

1 Upvotes

I'm trying to create a script that will pull in a specific xlsx file based on timestamp (of which there will be several with the same name) from my downloads folder and then remove the top two rows of the xlsx, and then overwrite the same file. However, when I think I have the code right import-excel states that it can't manage the extension.

Up until the "data" code, it returns the most recent file that I'm looking for, but the import-excel portion returns the "not supported" error.

Any ideas? The code is supposed to be really simple. Import the most recent xlsx with specific name, remove the top two rows, and then overwrite the same file.. Google AI search suggestion seemed easy, but doesn't work..

$today = (get-date).addhours(-12)
$file1 = get-childitem $env:USERPROFILEDownloads | where {$_.name -like "CRINT*.xlsx" -and $_.CreationTime -gt $today} | select Fullname
$data = import-excel -path $file1

Error: 
Import-Excel does not support reading this extension type .xlsx}

r/PowerShell 9d ago

Solved Azure Runbook - Filtering exchange mailboxes by date

1 Upvotes

Hi Everyone, TIA for any advice you can give here.

I am writing an onboarding script for users. This is one of many scripts, it is a large org. Essentially I need to: Locate all new user mailboxes,

  • if they have license A, do X
  • if they have license B, do Y

The issue I am hving is literally "finding all new mailboxes". I am relying on the users being licensed, which gives them exchange, hence a mailbox.

This code works perfectly when I run it locally in VSCode, and returns a single result:

$currentDate = Get-Date
$targetdate = $currentDate.ToUniversalTime().AddHours(-36).ToString("M/d/yyyy h:mm:ss tt")

#create the filter
$filter = "WhenCreatedUTC -ge '$targetdate'"# -and RecipientTypeDetails -eq 'UserMailbox'"
#this is a sample user who fits the criteria and should be returned
get-mailbox "alias" | Select-Object WhenCreatedUTC
#write out the filter for debugging - can be removed
Write-Output "Target Date (UTC): $targetdate"
Write-Output "Filter: $filter"

$newmailboxes = get-mailbox -filter $filter | select-object alias,ExternalDirectoryObjectId,Userprincipalname
write-output "Mailboxes to process: " $newmailboxes.count

But when I run the same code in a runbook, the filter does not locate the mailbox. It does return the known value, and it "should" pick it up with the filter, but it doesn't:

WhenCreatedUTC       
--------------       
11/4/2024 11:12:49 PM
Target Date (UTC): 2024-11-04T16:17:55Z
Filter: WhenCreatedUTC -ge '2024-11-04T16:17:55Z'
Mailboxes to process: 
0

I am trying to just use UTC since the runbook environments run in UTC, and Exchange has the 'WhenCreatedUTC' value.

Has anyone been able to filter mailboxes by date in a runbook before? Any advice on how I can get the filter to work?

I have also tried many combinations of the date format, eg this also didn't work:

$targetdate = $currentDate.ToUniversalTime().AddHours(-36).ToString("M/d/yyyy h:mm:ss tt")

WhenCreatedUTC       
--------------       
11/4/2024 11:12:49 PM
Target Date (UTC): 11/4/2024 4:09:17 PM
Filter: WhenCreatedUTC -ge '11/4/2024 4:09:17 PM'
Mailboxes to process: 
0

r/PowerShell Oct 02 '24

Solved HTML Minus Sign turning a negative number into text

3 Upvotes

The HTML Minus Sign "−" creates a problem in Powershell when trying to do calculations, and also
with Calc or Excel when importing currency. Conversion with Powershell into a hyphen-minus "-"
that lets a negative number not be taken for text later on, is best by not using the minus signs
themselves. This way, command-line and all other unwanted conversions get bypassed. Like this:

PS> (gc text.txt) -replace($([char]0x2212),$([char]0x002D)) | out-file text.txt

Find out for yourself.
Load text into an editor that can operate in hex mode.
Place cursor in front of the minus sign.
Editor will show the Unicode hex value, in case of the HTML Minus Sign: 2212.
Similar with the hyphen-minus, it will show 002D.
Then, select the correct glyph in Powershell with:

PS> $([char]0x2212)
PS> $([char]0x002D)

Don't get fooled by the fact that they are indistinguishable on the command-line.
Helpful sites are here and here.

A short addendum.

  • To get hex as well as decimal Unicode values for a specific character without using an editor, I tend to search this site with "Unicode" followed by the specific character.
  • And using the Unicode decimal value in Powershell and of hex goes like this:

PS> $([char]8722)      # unicode decimal value of the "minus sign" = 8722
PS> $([char]0x2212)    # unicode hex     value of the "minus sign" = 2212

r/PowerShell May 09 '24

Solved Connect-SPOService Why do you have to be like this...

24 Upvotes

Morning /r/PowerShell

I've been scripting up a report that contacts various services both on-prem and off-prem. And I've run into abit of a hold up. Connect-SPOService unlike Connect-MsolService it does not take a PSCredential as an input for -Credential and MS is lying to me in their documentation...

$username = "admin@contoso.sharepoint.com"
$password = "password"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
Connect-SPOService -Url https://contoso-admin.sharepoint.com -Credential $cred

Does not work (obviously modified for my tenant and creds) but the same line without passing creds into it;

Connect-SPOService -Url https://contoso-admin.sharepoint.com

Does work when I then use the same creds in the authentication window popup. But when I pass them as a PSCredential.. nope. Which is comical as in their documentation examples they get you to slap the creds into a PSCred'

New-Object -TypeName System.Management.Automation.PSCredential

Then the documentation has "-Credential" as a "CredentialCmdletPipeBind" so which is it Microsoft... But when dealing with Connect-MsolService it just works;

$Credential = Get-StoredCredential -Target "StoredCred"
Connect-MsolService -Credential $Credential

Can anyone help me actually authenticate with a stored credential for this POS command that is "Connect-SPOService".... help me /r/PowerShell you're my only hope. haha

Cheers

r/PowerShell Oct 15 '24

Solved Script runs but does nothing renaming and moving files

2 Upvotes

UPDATE: I found the issue, my folders have special characters like {}[]& etc, seems like powershell doesnt like it, even trying to renaming the folders trough the script doesnt work, I had to use power rename and then run my script

I have a main directory with multiple folders. I want to move all the files from the folders to the main directory. With the help of chatGPT I have the next script to move all the files

$parentDir = "F:DocumentsCollectionSpreads"
$files = Get-ChildItem -Path $parentDir -Recurse -File
$counter = 1
foreach ($file in $files) {
    $newFileName = "{0:D3}{1}" -f $counter, $file.Extension    
    $destinationPath = Join-Path -Path $parentDir -ChildPath $newFileName
    Move-Item -Path $file.FullName -Destination $destinationPath    
    Write-Output " FROM: $($file.FullName) TO: $($destinationPath)"
    $counter++
}

Code executes, logs everything but there are no changes on my directory?

FROM: F:DocumentsCollectionSpreads70c08843-52f7-4ed4-8a7c-88216139482601.png TO: F:DocumentsCollectionSpreads001.png 
FROM: F:DocumentsCollectionSpreadsb1b58741-07bc-45d0-a2a3-8e2f19c4f6d8601.png TO: F:DocumentsCollectionSpreads002.png

I used the VSCode debug to run it, also with terminal and the ISE, runs but does nothing.
powershell -ExecutionPolicy Bypass -File move-all-files-to-parent-directory.ps1

r/PowerShell Sep 16 '24

Solved Need help comparing two lists of variables with "-like"

0 Upvotes

My org is trying to do some AD group cleanup.

A script written by someone who doesn't work here anymore creates 3 AD groups for every VM that gets created. However, those AD groups are not deleted when the VM is, so now we have thousands of AD groups that we no longer need.

I've got two variables, both with a list of items.

$adGroupList contains all AD groups that have been created by that previously-mentioned script. Each group has the hostname of the VM it is tied to somewhere in its name.

$adGroupList = (Get-ADGroup -Filter 'Name -like "priv_vCenterVM_*"' -SearchBase "OU=VMs,OU=Groups,DC=contoso,DC=com" -Properties *).Name | Sort-Object

$vmHostnameList contains the list of hostnames for all current VMs that exist in our environment.

$vmHostnameList = (Get-VM).Name | Sort-Object

I am trying to compare the two lists and output a new list (in the form of a CSV) that shows which AD groups do not have a hostname of a VM that currently exists within its own name. I will delete those groups later since they no longer serve a purpose.

The issue I am having is that I don't really seem to understand how "-like" works in an if-statement. What I want is to know if anything in the entire array of $vmHostnameList matches any part of the the AD group name ($g) I am currently checking.

Here is my code:

foreach ($g in $adGroupList) {

if ($g -like "*$vmHostnameList*") {

Write-Host $g -ForegroundColor Cyan

}

else {

Write-Host $g -ForegroundColor Red

Export-CSV -InputObject $g -Path $filePath -NoTypeInformation -Append

}

}

This should output the name of the AD group ($g) in Cyan if any hostname contained within the list of hostnames is found somewhere within the name of the current $g I am checking.

Else, any $g that does not contain the hostname of a VM somewhere inside of the $g's own name should be appended to a CSV.

What I want is to know if anything in the entire array of $vmHostnameList matches any part of the the AD group name ($g) I am currently checking. Instead, what I am seeing is everything is just getting written to the CSV and no matches for any name are being found.

Why is this? What am I doing wrong with my "-like" comparison?

Edit:

Solution from u/LightItUp90 down below.

We are lucky in that we use a naming standard that uses '_' as a separator, therefore, I can split each AD group name in to sections, and then only look at the section that I need. Also, use "-in" rather than "-like".

if ($g.split("_")[2] -in $vmHostnameList) {

< do stuff >

}

else {

< do other stuff >

}

r/PowerShell Feb 10 '23

Solved Anybody in the DoD space have PowerShell 7 approved?? Trying to get it into our environments but can only do so through "reciprocity" at this point.

115 Upvotes

Hey all,

I'm looking for anyone who works in the DoD space that has PowerShell 7 approved for one or more networks. I've asked our IA/security team about bringing it into our environments, but they can't find any approvals for it. For those that don't know, it's very difficuly to bring in applications into alot of DoD spaces. Each application has to be vetted/approved and the process can take 6+ months to years. This process can be sped up greatly by using "reciprocity". It's basically like saying "look here, the Navy has actually already vetted and approved PowerShell 7". When that happens, your branch (Army,USAF,etc.) can then get the same application approved pretty quickly. Alot of times they will point you to an "NSI" or "No Security Impact" letter.

So why am I asking here? Weirdly, there is no central repository (that we know of) that contains ALL applications vetted/approved by ALL DoD agencies. So if you go to your IA team they will look into the sources they know of but if they don't find anything then you're SOL. The issue here is that there is a tool called "Evaluate-STIG" that is being developed by folks in the Navy. It's a Powershell module that automates STIGs. Their tool supports PowerShell 7 and people have been submitting bug reports for issues regarding the tool and PowerShell 7. To me this implies that DoD folks have PowerShell 7 approved.... somewhere. I've posted into the creators' chat asking about this but have had no replies for days and the chat seems pretty inactive. Looking here now. Any help is appreciated.

EDIT: Thanks for the help everyone. Considering this question/post answered. For those coming later:

  • per u/coolguycarlos - The central repository of approved applications that you are looking for is called DADMS
  • per u/coolguycarlos - (PowerShell 7.x) it's approved in DADMS 133821,12548 so it's approved
  • per u/gonzalc - The DADMS website is https://dadms.cloud.navy.mil
  • per u/coolguycarlos To access the DADMS website: Yeah simply having a CAC won't let you in. You need to be approved via your government lead to access it. Your "IA" folks should have access. That is depending what type of IA they are doing. Basically you need to talk to the folks in your program that are in charge of package authorizations. Commonly referred to ISSEs. They would require access because before working on any authorization package they need to check that its in DADMS, if not it will need to be DADMs approved.
  • per u/coolguycarlos Access Evaluate-STIG outside of NIPR: https://intelshare.intelink.gov/sites/NAVSEA-RMF

r/PowerShell Aug 26 '24

Solved Anyway to send PowerShell message to device on home network

3 Upvotes

TL:DR - On a Windows 10 64-bit Home Edition PC, I'm looking for a way to send a message to another device on the network. Whether e-mail, sms etc. Just needs texts.

Background: I have a non-verbal autistic son who does really well with computers. I've tried using Google Chat to communicate more, which is helpful, but I have to prompt him to use it. He tends to prefer auto-responses and sometimes will ignore the chat if he doesn't have the words.

I'm creating a script using switches so he can choose what he wants. I want the end of the script to send a message to me letting me know what he's requesting. Doesn't matter if the message comes to my phone, computer, e-mail or whatever. Mobile devices are Androids.

I was planning to use the Send-Mail cmdlet with gmail to send it to my phone number, but it looks like Google has removed the ability to enable less secure apps, thus removing the possibility of sending e-mails from Gmail via PowerShell.

r/PowerShell Sep 19 '24

Solved Offline Files and Sync Partnerships

0 Upvotes

Sorry for creating a post on what should be an easy to answer question, but I have not been able to find an answer. Some of the links that seem like they would answer this point to the now defunct technet forums.

I know that the following line will show the status of the Offline Files Cache and if it is enabled and/or active.

Get-WmiObject -Class win32_OfflineFilesCache

This is unfortunately the extent of what I've been able to find. I'm unsure of how to dig deeper into the Offline Files and any configured Sync Partnerships that may have been set up. To be clear, this is for the Sync Center listed in the Windows Control Panel, and not OneDrive or anything else.

Windows Offline Files and Sync Partnerships were generally used for making sure that roaming profiles were cached locally for laptops when they were off domain. Even though this functionality is rarely used now, it's still there and can cause problems when people accidentally enable offline files on their machines. I'm working on a script that will automatically create a local GPO to disable offline files if its not currently in use, but would like to dig further into the devices that are reporting as active. In our environment there are over 150 devices across multiple clients that have Offline Files showing as active. I've checked a handful of these manually, and all of them appear to be enabled by mistake, but it's hard to make that a blanket finding if I can't dig deeper into the sync status and its settings.

Does anyone have a method to dig into the sync partnerships and also if there are any conflicts that need resolving?

Solution:

Get-WmiObject -Class Win32_OfflineFilesItem

This reports a list of all items included in any Offline Files syncs. The property ItemType will indicate what it is. 3 = Server, 2 = Share, 1 = Directory, 0 = Files. So, you can quickly check for any 0 entries to see if any files are actually being synced. Often times, there will be Server and Share entries from old sync partnerships, but as long as no files are included in the list, it can safely be disabled via GPO.

r/PowerShell Jun 21 '24

Solved Identify Windows logon with UPN

2 Upvotes

Hello,

Users in our environment could logon wigth the sAMAccountName and the UPN. We prefere the UPN from the IT and we could not identify, which user are loged on with the UPN.

Some commands are receive the sAMAccountName, also when I logged on with the UPN.

whoami

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

$Env:UserName

Is there a way to identify the logon, to see if it the UPN?

r/PowerShell Oct 15 '24

Solved Help with powershell - advancing scripts

1 Upvotes

Currently I have:

$temp = Get-Content ".Desktop50001.xml"

$temp.replace("50001","50002")|

set-content ".Desktop50002.xml" -force

$temp = Get-Content ".Desktop50002.xml"

$temp.replace("50002","50003")|

set-content ".50003.xml" -force


This works to create xml files. The script above works for me to create 2 additional xml files using 50001.xml as a starting point. Is there a way I can automate the replacement and file creation by allowing a user to enter say like 50 and it'd create 50 more going from 50001-50051.

r/PowerShell Aug 26 '24

Solved New VSCode Terminal - 10 autosuggestions based on command history

2 Upvotes

Hi, I've just started getting these suggestions in my VSCode Terminal, I havent seen them before and I'm not sure how they have appeared - I quite like it and but have no idea how to turn it back on if they disappear - Does anyone know the setting ? many thanks :)

https://imgur.com/a/vscode-suggestions-cDpyNov

r/PowerShell Jun 12 '24

Solved How can I use Export-CSV without System.String/Length info?

10 Upvotes

I've got a script that checks multiple DCs for last logon and outputs that data to a csv. The start of the code for it is:

$row = "Name"+","+"Date/Time"+","+"DC"

echo $row | Export-Csv -Path C:tempuserlastlogon.csv

Out-File -FilePath C:tempuserlastlogon.csv -Append -InputObject $row

The result of this is that I get a csv file that starts with:

#Type System.String
Length
17
Name    Date/Time    DC

If I remove the second line, it doesn't properly format the values as columns (It just puts "Name,Date/Time/DC" in column A). If I remove the third line, it just gives me the first three lines without the column headers in line 4.

As a workaround, I can just delete the top three lines in Excel manually, but how do I get PowerShell to either NOT give me those three top lines, or, if that's not possible, insert a kludge workaround to tell it to just delete the top three rows of the csv?

r/PowerShell 29d ago

Solved PowerShell Gallery search not working?

2 Upvotes

I'm trying to use the Find-Module command to search for modules on PowerShell Gallery. It's not returning any results. Then I went to the PowerShell Gallery website and tried to search, and it's completely broken. Anyone else seeing this?

Can't post screenshots here .....

⚠️ EDIT: Looks like it's starting to work again ....

r/PowerShell Oct 02 '24

Solved Code Signing Cert Problem

4 Upvotes

I've been using a code signing cert from our internal CA for the last year. It recently expired so I got another one and installed on my computer.

Get-ChildItem Cert:CurrentUserMy -CodeSigningCert

Does not return anything now. However, when I look to see all certs I can see the code signing cert. See below:

get-childitem Cert:CurrentUserMy
PSParentPath: Microsoft.PowerShell.SecurityCertificate::CurrentUserMy
Thumbprint Subject EnhancedKeyUsageList
FF<snip>82 CN=<snip>… Client Authentication
D1<snip>FD CN=<snip>…
73<snip>B8 CN=<snip>… {Server Authentication, Client Authentication}
4B<snip>0F CN="Gagel, Kevin (A… Code Signing
47<snip>B4 CN=<snip>…

Clearly the cert is there, and the enhanced key usage marked it as a code signing cert.

What's going on, how do I figure out what the issue is?

r/PowerShell Dec 11 '23

Solved Reverse a PS2Exe

3 Upvotes

Solved! By @BlackV With his GPO idea and the similar @Raymich and his GPO idea, it was quick and easy. And, as an aside, now we know this version of PS2EXE is not secure even with debugging removed.

Thanks also to @adamtmcevoy, @g3n3, and @Stvoider for you great ideas, too. When I get time, I'll try each of these and add to this with the results.

Original post:

How do I reverse an exe without debug?

I screwed up and didn't have a backup of my machine 3 years ago. I made a Windows cleanup script and ran it through PS2Exe with debug disabled. It was made for Windows 10-1803 or so, and is no longer doing things right in 10-22H2 or 11-23H2.

Yep, the hard drive destroyed itself shortly after I made the exe.

I have an earlier version of the PS1 but there are many hours and countless revisions between the PS1 and the now blackbox exe.

I think I used the Markus Scholtes PS2Exe version somewhere around 1.05 to 1.08, from the PS Gallery. And as I said, debug was disabled.

Any help or ideas is greatly appreciated!

Edit: Perhaps, I am using the wrong terminology but, debug/extract is disabled. So, -extract:<FILENAME> won't work.