/r/PowerShell

Photograph via snooOG

PowerShell is a cross-platform (Windows, Linux, and macOS) automation tool and configuration framework optimized for dealing with structured data (e.g. JSON, CSV, XML, etc.), REST APIs, and object models. PowerShell includes a command-line shell, object-oriented scripting language, and a set of tools for executing scripts/cmdlets and managing modules.

ABOUT POWERSHELL

Windows PowerShell (POSH) is a command-line shell and associated scripting language created by Microsoft. Offering full access to COM, WMI and .NET, POSH is a full-featured task automation framework for distributed Microsoft platforms and solutions.


SUBREDDIT FILTERS

Desired State Configuration

Unanswered Questions

Solved Questions

News

Information

Script Sharing

Daily Post

Misc








/r/PowerShell

266,095 Subscribers

0

Remote Launch of VR Game on Windows PC via SSH

Hey everyone,

I hope this is the right place to ask—I'm really stuck and could use some advice!

Setup:

  • Ubuntu Server (24.04): Hosting several services and frontend in Docker containers.
  • Windows 11 PC: Local account "User" with a VR game executable and a Meta Quest 3 connected via Link Cable.
  • The VR game listens to some UDP ports for game and control data.

Current Situation:

Until now, I started the game manually on the Windows PC, and everything worked perfectly. Now, I need to start the game remotely from a backend (node.js) service on the Ubuntu server.

Here's what I've done so far:

  1. Established an SSH connection between the Ubuntu server and the Windows PC.
  2. Tried using PsExec with the following command:

PsExec \\PC-Name -i 1 -u User -p password -d -h "C:\\Users\\User\\Desktop\\game\\gameVR.exe"

This passes the correct user and password context because the game needs it to recognize the VR headset.

Problem:

When starting the game this way, it doesn't seem to have permission to access network communications—the game isn't receiving any of the UDP messages, even though they are being sent to the Windows PC.

Other Attempts:

I tried invoking a PowerShell script via SSH to launch the game. However, this only starts the process and doesn't bring up the UI.

Question:

How can I remotely launch this game with all components (UI, network, and VR integration) working correctly? Any help, suggestions, or insights would be greatly appreciated!

Thanks in advance!

2 Comments
2024/12/02
12:23 UTC

1

So, Microsoft.Graph.Entra... Has anyone done some extensive testing?

Hi r/PowerShell!

MS aims for general availability of Microsoft.Graph.Entra by the end of 2024, so I thought I'd take a closer look.

So far I'm... confused.

I only tested a couple of cmdlets and found that they're essentially identical to their Microsoft.Graph... equivalents. They seem to run slower, though.

Has anyone here done some extensive testing and found a reason why should we switch?

Cheers!

2 Comments
2024/12/02
11:53 UTC

5

Migration Fileserver Inheritance 🤯

A company decided to migrate data from an old Windows Server 2012 to a new Azure storage account.

We decided to use Robocopy for the migration process, but in the meantime I am wondering how to get all the broken inheritance permissions with poweshell

wserver2012 does not support long path and I was wondering if anyone had found a solution via a powershell script

15 Comments
2024/12/02
10:17 UTC

3

is this command working?

so i wanted to see what my biggest file in order, and i saw a reddit comment to use this command instead installling an anything.exe to see my storage. so i gave a shot.
Get-ChildItem -Recurse | Select-Object -Property Length, Name | Sort-Object -Property Length | Format-Table -AutoSize what it does

then i had waited for like 20 minutes... nothing happend...

12 Comments
2024/12/02
03:35 UTC

0

How can I get the system’s last DirSync in PS7?

Hey all. I’m currently as part of a script using the msolservice module to get the time of the last system sync.

However, due to msonline being depreciated, I’m going to need to find a new command, using ExchangOnline or MGGraph preferably.

Does anyone have any suggestions? I’ve dug around a bunch but can’t for the life of me find another command set for getting the last sync time of the server (as opposed to mobile sync for one account, etc).

2 Comments
2024/12/02
02:13 UTC

0

Need Assistance with Script

I recently came across the following script (from remote access - Powershell - how to check logged users in specific Machines - Stack Overflow ) and it works PHENOMENAL locally. It's not my own but has come in REALLY handy.

I am trying to manipulate it so that I can use it remotely on PC names on the network. I've tried making it a 'read-host' option for $ComputerName, but see 'localhost' is also tied to $Computername. Not sure if an array is necessary to add to the code? I am only spit-balling given my limited knowledge of PS coding (but am pretty good at tearing it apart and putting it back together! lol)

Function Get-LoggedOnUser {

param(

[CmdletBinding()]

[Parameter(ValueFromPipeline=$true,

ValueFromPipelineByPropertyName=$true)]

[string[]]$ComputerName = 'localhost'

)

begin {

$ErrorActionPreference = 'Stop'

}

process {

foreach ($Computer in $ComputerName) {

try {

quser /server:$Computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {

$CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'

# If session is disconnected different fields will be selected

if ($CurrentLine[2] -eq 'Disc') {

[pscustomobject]@{

UserName = $CurrentLine[0];

ComputerName = $Computer;

SessionName = $null;

Id = $CurrentLine[1];

State = $CurrentLine[2];

IdleTime = $CurrentLine[3];

LogonTime = $CurrentLine[4..($CurrentLine.GetUpperBound(0))] -join ' '

}

# LogonTime = $CurrentLine[4..6] -join ' ';

}

else {

[pscustomobject]@{

UserName = $CurrentLine[0];

ComputerName = $Computer;

SessionName = $CurrentLine[1];

Id = $CurrentLine[2];

State = $CurrentLine[3];

IdleTime = $CurrentLine[4];

LogonTime = $CurrentLine[5..($CurrentLine.GetUpperBound(0))] -join ' '

}

}

}

}

catch {

New-Object -TypeName PSCustomObject -Property @{

ComputerName = $Computer

Error = $_.Exception.Message

} | Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error

}

}

}

}

8 Comments
2024/12/02
02:01 UTC

7

Suppress console output for entire script/cmdlet

I have a script that generates some output that is not needed (such as from the New-Item cmdlet and many others) and disrupts the output that the user actually cares about. I know that I can add Out-Null (or one of the other output to $null alternatives) on each command/line, however, I was wondering if it's possible to set something up on the script level to stop these types of commands from producing output?

11 Comments
2024/12/01
20:31 UTC

46

What have you done with PowerShell this month?

77 Comments
2024/12/01
12:00 UTC

2

Help with working with command output

Ok, this is probably really beginner stuff, sorry about that. Hopefully someone can help.

I'm trying out this MQTT module from here:

Link removed becuases of spam filter?

My code is:

$Session = Connect-MQTTBroker -Hostname  -Port 1883 -Username **** -Password (ConvertTo-SecureString -String '****' -AsPlainText -Force)
Watch-MQTTTopic -Session $Session -Topic "helvetti/#"192.168.1.2

It works, it's listening to the topic and I get output with payload:

Listening...
Timestamp           Topic                      Payload
---------           -----                      -------
1.12.2024 0.00.10   helvetti/192.168.1.2       { "command": "up", "args": "start" }

The goal is to do something when the payload is "X". Run some command with perhaps the payload as an argument.

Any ideas how I would go about doing this? My first guess was trying to capture the output as an array, but have not been able to figure out how. Perhaps that's not even the best way to go about this. Any suggestions are welcome.

11 Comments
2024/12/01
09:34 UTC

1

How do I turn on and off metered network using powershell

Hi everyone I tried asking copilot how to turn on metered network and it didn't really give an answer. I did find a script to add something to registry to try change the value but it won't work. I left the code on another computer but it was basically REG ADD filename.reg

So my question is does anyone have an easier way to turn metered network on and off?

What I'm wanting to do is pause onedrive sync during the day and then enable it early in the morning so then my files can sync.

If I can't do that then maybe a way to run the script to open the window to manually turn it on and off as this is going to be a daily thing I'd rather make this automated.

Thanks in advance.

11 Comments
2024/12/01
06:21 UTC

14

Importing specific Graph modules taking 5 minutes...

Importing what I need for Graph with:

Import-Module Microsoft.Graph -Function Get-MgUser, Get-MgGroup, Get-MgDirectoryObject, Update-MgUser, Update-MgGroup, Update-MgDirectoryObject

It's taking like 5 minutes, is there a better way to do this?

16 Comments
2024/11/30
00:09 UTC

7

Add users to Network Configuration Operators Group - failing

Hi there,

I've had some fun with Powershell this evening (never thought I'd say that). Co-Pilot has been really helpful with writing me a script which should save me hours with deploying Wireguard VPN to users next week which is amazing.

There is just one portion of the script that seems to be completely failing. It's not writing any failures or successes at all, almost as if it's completely missing this portion of my script.

The idea is that it looks to see which users use the device and then adds them to the Network Configuration Operators group. However it's not happening. Local users ARE being added. However now I have asked it to look for AzureAD and Domain Users it's completely failing to add anything and also is not reporting any errors back to me.

I've manually looked at Event ID 1531 and it's empty.

  1. Where-Object { $.Id -eq 1531 -and $.Properties[1].Value -like "@" }:
    • This filters the events to include only those with an ID of 1531 and where the second property (index 1) contains an "@" symbol, indicating an email address (typically used for Azure AD or Domain users).

None of the Users within Event Viewer appear to have an @ symbol either. For instance AzureAD\JoeBloggs shows with event IDs 1, 3, 4 etc. Should I be using one of these?

Any help greatly appreciated!

# ** Add user to Network Configuration Operators Group
# Get a list of all local users
$LocalUsers = Get-LocalUser | Where-Object { $_.Enabled -eq $true }

# Check if the group exists
$GroupExists = Get-LocalGroup | Where-Object { $_.Name -eq "Network Configuration Operators" }
if (-not $GroupExists) {
    Write-Output "The 'Network Configuration Operators' group does not exist."
    Log-Message "The 'Network Configuration Operators' group does not exist." -IsError
    exit 1
}

foreach ($User in $LocalUsers) {
    try {
        Add-LocalGroupMember -Group "Network Configuration Operators" -Member $User.Name
        Write-Output "Added $($User.Name) to the Network Configuration Operators group."
        Log-Message "Added $($User.Name) to the Network Configuration Operators group."
    } catch {
        Write-Output "Failed to add $($User.Name) to the Network Configuration Operators group: $_"
        Log-Message "Failed to add $($User.Name) to the Network Configuration Operators group: $_" -IsError
    }
}

# ** Add Azure AD and Domain users who have logged on to the target PC
try {
    $LoggedOnUsers = Get-WinEvent -LogName "Microsoft-Windows-User Profile Service/Operational" | 
                     Where-Object { $_.Id -eq 1531 -and $_.Properties[1].Value -like "*@*" } | 
                     Select-Object -ExpandProperty Properties | 
                     Select-Object -ExpandProperty Value | 
                     Sort-Object -Unique

    foreach ($User in $LoggedOnUsers) {
        try {
            Add-LocalGroupMember -Group "Network Configuration Operators" -Member $User
            Write-Output "Added $User to the Network Configuration Operators group."
            Log-Message "Added $User to the Network Configuration Operators group."
        } catch {
            Write-Output "Failed to add $User to the Network Configuration Operators group: $_"
            Log-Message "Failed to add $User to the Network Configuration Operators group: $_" -IsError
        }
    }
} catch {
    Write-Output "Failed to retrieve or add Azure AD and Domain users: $_"
    Log-Message "Failed to retrieve or add Azure AD and Domain users: $_" -IsError
}
10 Comments
2024/11/29
21:26 UTC

1

User Permisson for COM Objects

Hi,

i have a larger script with a special part where it always gets an access denied error when the User is not a local admin.

$RemoteMachine = "certserver"
$Credential = Get-Credential "domain\certuser"
$ScriptBlock = {
$CaView = New-Object -ComObject CertificateAuthority.View
$CaView.OpenConnection("certserver\Local-CA")
$CaView | Get-Member
}
Invoke-Command -ComputerName $RemoteMachine -Credential $Credential -ScriptBlock $ScriptBlock

The error i get all the time is:

[certserver] Connecting to remote server certserver failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.

+ CategoryInfo : OpenError: (certerver:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken

Because i'm rather new to handle ComObjects, anyone an idea what permissions do i have to give this certuser so he can query the CetificateAuthoritiy ComObject without granting Local Admin?

I had a look at dcomcnfg but could not find anything usefull.

Thanks in advance

0 Comments
2024/11/29
13:43 UTC

0

Script not running as task

This script worked fine until I had to upgrade to PS7

I have trimmed it down tot he following

Start-Transcript -Path "C:\users\<user>\Desktop\log.txt"
$inputPath = "<pathtofiles>"

$inputFile = Get-ChildItem -Path $inputPath | Where-Object { $_.Name -like "*StudentList-NoGroupings.csv" }  | Sort-Object LastWriteTime | Select-Object -Last 1

Write-Host "inputFile = $inputFile"

try
{
    $excel = New-Object -ComObject excel.application
    Write-Host "excelObject made"

    Start-Sleep -seconds 10  ##added just as a test

    $wb = $excel.workbooks.open("$inputFile")  ##this is where it fails
    Write-Host "wb opened"

    $sh = $wb.Sheets.Item(1)
    Write-Host "sh opened"

    ## lots of code removed for testing

    $wb.Close()
    $excel.Quit()

    Rename-Item "$inputFile" -NewName "$inputFile.done"
    Write-Host "done"
}
catch 
{
    Rename-Item "$inputFile" -NewName "$inputFile.failed"
    Write-Host "ex =  Error=$_"
}

Stop-Transcript

This runs fine if I run it manual. it also runs fine as a task if I select "run only when user is logged on" option in task scheduler. If I select the "Run whether user is logged on or not" option using the same user as I am testing with I will get the following errors when the workbook is attempted to be opened.

Error=Microsoft Excel cannot access the file '<pathtofiles>\2024Nov28120024_StudentList-NoGroupings.csv'. There are several possible reasons:

• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.

The file exists and is not locked as the rename-item in the catch block works and will append .failed

I am trying to open a workbook so I have no idea what the 3rd suggestion is about.

Anyone have any suggestions on what I can try here? It looks like a issue with how this is running as apposed to a code issue but I have no idea what else I can try..

Thanks

20 Comments
2024/11/28
22:57 UTC

0

Total Beginner - Need a very simple script

I suffer from ME/CFS - been off work years

I've got a MariaDB backend running for my Kodi setup & I want to very simple backup

  1. use maria-dump.exe

  2. put on my server

  3. have it use today's date as filename produced

    "C:\Program Files\MariaDB 11.5\bin\mariadb-dump.exe" -u root -p123 -x -A > \truenas\vault\mariadb-dump(Get-Date -Format dd-MM-yyyy).sql

is basically the command I need to run as I want the date to be in dd-MM-yyyy format

Then I can schedule a dump of the TV series in task scheduler - the files are 100k and take 5 secs to produce. So I'll have a folder of dump files and can manually delete the oldest as and when

I've tried messing around with "&" and "Start-Process -NoNewWindow -FilePath" but I'm running into errors and getting very confused (no good with ME/CFS)

6 Comments
2024/11/28
17:29 UTC

12

Copy-UserInternationalsettingstosytem

Hi All,

This Powershell cmdlet (Copy-UserInternationalsettingstosystem ) is available in windows 11 which will copy current user's regional settings to Welcome screen & System accounts and new user's accounts.

This cmdlet is not available in windows 10. Do we have any powershell cmdlet equivalent command in windows 10 to same perform functionality?

Any suggestions?

3 Comments
2024/11/28
14:46 UTC

0

Question about my copy script

Hello everyone,

To be directly honest about it, as I'm yet to bad to do it my myself, I used AI to help me for this script, even if I planned to learn it correctly by myself.

I want to copy files from a directory on a external hard drive to a second one (files from the first dir are correct photos that replace non correct photos on the second drive). Problem, the names of directories are not the same from a drive to another, but the names of the files inside are the same. There is also the case of files from second the second drive that are not present on the 1st one, that I need to let untouched.

Now the main problem of my script : at the beginning works well, but after some folders, I suppose because of the amount of files, it crashes and my computer with it. What can I do to correct this problem ? Thank you.

# Settings
$Dossier1 = "F:\LEAD\Dossier 1"
$Dossier2 = "F:\LEAD\Dossier 2"
$Rapport = Join-Path $Dossier2 "rapport_anomalies.txt"

# Report
if (Test-Path $Rapport) {
    Remove-Item $Rapport -ErrorAction SilentlyContinue
}
New-Item -Path $Rapport -ItemType File -Force | Out-Null

# Check dir
if (!(Test-Path $Dossier1)) {
    Write-Error "Le dossier source $Dossier1 est introuvable."
    exit
}
if (!(Test-Path $Dossier2)) {
    Write-Error "Le dossier destination $Dossier2 est introuvable."
    exit
}

# Replace TIF trough all sub-dir
function Remplacer-FichiersTIF {
    param (
        [string]$Source,
        [string]$Destination
    )

    # Get all TIF
    $FichiersSource = Get-ChildItem -Path $Source -Recurse -Filter "*.tif" -ErrorAction SilentlyContinue
    $FichiersDestination = Get-ChildItem -Path $Destination -Recurse -Filter "*.tif" -ErrorAction SilentlyContinue

    # Index of dest. files by name
    $IndexDestination = @{}
    foreach ($Fichier in $FichiersDestination) {
        $IndexDestination[$Fichier.Name] = $Fichier
    }

    # src files
    foreach ($FichierSource in $FichiersSource) {
        $NomFichier = $FichierSource.Name

        if ($IndexDestination.ContainsKey($NomFichier)) {
            $FichierDestination = $IndexDestination[$NomFichier]

            # Files length
            $TailleSource = (Get-Item $FichierSource.FullName).Length
            $TailleDestination = (Get-Item $FichierDestination.FullName).Length

            if ($TailleSource -ne $TailleDestination) {
                # Replace if length not the same
                Copy-Item -Path $FichierSource.FullName -Destination $FichierDestination.FullName -Force -ErrorAction Stop
                Write-Host "Remplacé : $($FichierSource.FullName) -> $($FichierDestination.FullName)"
            } else {
                # Not replaced if same length, report
                Add-Content -Path $Rapport -Value "NON REMPLACÉ (même taille) : $($FichierSource.FullName)"
                Write-Host "Non remplacé (même taille) : $($FichierSource.FullName)"
            }
        } else {
            # Report if file don't existe in Dir 2
            Add-Content -Path $Rapport -Value "ANOMALIE : $($FichierSource.FullName) non trouvé dans le dossier 2"
            Write-Host "Anomalie : $($FichierSource.FullName) non trouvé dans le dossier 2"
        }
    }
}

# Execute
try {
    Remplacer-FichiersTIF -Source $Dossier1 -Destination $Dossier2
    Write-Host "Traitement terminé. Rapport d'anomalies : $Rapport"
} catch {
    Write-Error "Erreur critique : $($_.Exception.Message)"
}
5 Comments
2024/11/28
14:39 UTC

0

PowerShell script help urgently (I can pay for the script)

I need a powershell script that transfers files from source to destination everytime a new file gets in the source, every 5 minutes.

I currently have the process but there’s a big delay, i want to be able to transfer multiple files at the same time within the script.

62 Comments
2024/11/28
14:38 UTC

2

Weird Characters

Hi all,

I have a script I run as an azure runbook that writes signatures to Exchange Online and drops an HTML file in user's Onedrive folders for a scheduled task to pick up and implement in outlook. I've made a new change to add a Dad Joke to the signature (I'm a new dad...) but am having some issues with weird characters showing up it looks like in replacement of commas and apostrophes. I'm not sure at what point they are introduced. When I run this in powershell locally, it works fine:

$DadJoke = Invoke-RestMethod -Uri  -Headers @{accept="text/plain"};Write-Output "$DadJoke" -Verbose

What's a ninja's favorite type of shoes? Sneakers!https://icanhazdadjoke.com/

When it's run in Azure it has issues with some characters:

There’s a new type of broom out, it’s sweeping the nation.

Edit: Looks like the issue is in the character encoding in Azure Runbooks. it's not able to handle non-ASCII characters. Since some of the jokes contain non-ASCII characters (such as smart quotes) they don't come out right. I didn't find a way to replace those and filtering them out makes the sentances weird, so I'm just skipping them:

$DJ = Invoke-RestMethod -Uri https://icanhazdadjoke.com/ -Headers @{"accept"="text/plain"}
while($dj -match '[^\x20-\x7F]'){
    write-output "Bad Joke $DJ"
    $DJ = Invoke-RestMethod -Uri https://icanhazdadjoke.com -Headers @{"accept"="text/plain"}
}
write-output "Good Joke $DJ"
17 Comments
2024/11/28
02:43 UTC

3

Looking for feedback on scripting - Set-EntraIDExtensionAttributes.ps1

I've been learning/working with Powershell for about two and a half years now, but I don't work with anyone that possesses much greater knowledge than I have, that also has time for any kind of code review. I've also never posted anything online unless I was looking for something specific that I wasn't able to get working myself. So, with the holiday coming up and not much to do at work, I thought this might be a good time to put one of my scripts out there and see if I could get some feedback.

Set-EntraIDExtensionAttributes.ps1 on GitHub

Thanks in advance.

2 Comments
2024/11/27
22:50 UTC

1

Can I have two arrays attached to "body" in New-Object Net.Mail.MailMessage

# mail object
$SMTPServer = "mail.blah.com"

$msg  = New-Object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($SMTPServer)

$msg.From       = "fred@blah.com"
$msg.ReplyTo    = "noreply@blah.com"
$msg.Subject    = "This is the subject header"
$msg.IsBodyHtml = "True"
$msg.Body       = "$htmlReport"
$msg.To.Add("mikejones@blah.com")

Side note, $htmlReport is the array converted to HTML and I add an HTML head, etc.  My question is, can I add two items to the $msg.Body?   

For example, I tried this and it didn't work.

$msg.Body = "$htmlReport"
$msg.Body = "$htmlReport2"

I have not tried "$htmlreport","$htmlReport2" just yet but wanted to post this hoping someone could correct me before I spend hours trying to figure this out.
8 Comments
2024/11/27
21:24 UTC

2

Can Someone help me remove this line "Loading personal and system profiles took 1746ms." from my powershell without me disabling the $Profile

I Tried using -nologo it works when u open it using a shortcut but if i use the address bar of explorer it does not work.

Some more unecessary information i recently discovered a ps script called winfetch and using that i am tryng to make it look aesthetic thats why i want to remove the line.

9 Comments
2024/11/27
20:07 UTC

2

Exporting "Generic.List[PSObject]" to CSV doesn't work

EDIT: Solved, thank you u/derohnenase

I am doing an audit script with a list instead of arrays and I am feeling I went down the wrong path with this.

List is formatted as

$list = New-Object System.Collections.Generic.List[PSObject]

ForEach loop pumps in PC names and local admins and then adds to list via

$list.Add($server_data)

List shows correctly in command line properly as ..

###########################################

Server Administrators Status

------ -------------- ------

Server1 N/A Unable to Connect

Server2 Administrator, Domain Admins Online

##############################################

But the export-csv file just shows the likes of ..

#########################

#TYPE System.Object[]

"Count","Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized"

"1","1","1","1","System.Object[]","False","True","False"

"1","1","1","1","System.Object[]","False","True","False"
###############################

I never had the problem with doing basic arrays but I read use lists as its more efficient than += into arrays. Speed wont help me if I cant really get the data into a csv file. DId I go down wrong path or am I missing something?

EDIT: Whole script for reference...be gentle im not Guru of powershell :)
****************************************************************************************

$servers = Get-ADComputer -Filter {(OperatingSystem -like "*Windows*Server*") -and (enabled -eq "true")}
$list= @()
$list = New-Object System.Collections.Generic.List[PSObject]
$localGroupName = "Administrators"
$total = $servers.count
$current = 0



#for each with count for status update on script
ForEach ( $server in $servers){
$current += 1

Write-Host "Working on $current of $total"

$testcon = Test-NetConnection -Computername $server.DNSHostName 

If ($testcon.PingSucceeded -eq $false){ 

#if connection test fails post status as such

$dataping = @([PSCustomObject]@{"Server" = $server.Name ;"Administrators" = "N/A";"Status" = "Error No Ping"})

$List.add($dataping)}

If($testcon.PingSucceeded -eq $true ){



 # Try to establish a remote session to the server and get local admins
    try {
        $session = New-PSSession -ComputerName $server.DNSHostName -ErrorAction Stop
        
        # Retrieve the members of the Local Administrators group
        $members = Invoke-Command -Session $session -ScriptBlock {
            $group = [ADSI]"WinNT://./Administrators,group"
            $members = $group.Invoke("Members") | foreach { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) }
            $members
        }
        
        # Add server and its administrators to the results array
        $data = @([PSCustomObject]@{"Server" = $server.name ; "Administrators" = $members -join ', ' ; "Status" = "Online"})
        $List.add($data)

           # Close the remote session
        Remove-PSSession -Session $session
    } catch {
    # If connection failed post Status as such    
       $datafailed = @([PSCustomObject]@{"Server" = $server.Name ;"Administrators" = "N/A";"Status" = "Unable to Connect"})
       $List.add($datafailed)
        }}}


#have to out-file to .txt cause thats the only thing that works
$list | out-file "c:\output\Localadmins.txt"
19 Comments
2024/11/27
18:13 UTC

9

Learning powershell, having trouble with function arguments

TLDR: I cannot pass -A to my function via an alias. I am trying to create some aliases for git commands (like I did for bash).

I have defined a function like this:

function GIT-ADD {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$false, Position=0)]
        [string]$addArgs,

        [Parameter(Mandatory=$false, ParameterSetName='Named')]
        [string]$NamedAddArgs
    )

    if ($PSCmdlet.ParameterSetName -eq 'Named') {
        git add $NamedAddArgs
    } else {
        git add $addArgs
    }

and made an alias for it Set-Alias -Name gita -Value GIT-ADD

I tried this as well

function GIT-ADD {
	param(
	    [Parameter(Mandatory=$true)]
            [string] $addArgs
	)
	git add $addArgs
   

It seems like the -A which is a legal git add option, does not work.

What do I need to change to fix my alias/function definition?

edit: I call the function/alias like this: gita -A

10 Comments
2024/11/27
17:22 UTC

2

Taking only the first X objects in a group.

I am importing data to a new system and have it in a csv with numerous rows. In most cases we want to import everything but sometimes we only want the first 5 (for example). I have the csv sorted and am thinking there must be a way to use group-object and only pull in a limited number that I specify. In this something I can do with group-object? For example: Name, State, revision. Jim, OR, aaa Tom, OR, bbb Dave, OR,cccv Dan, TX, yyyy George, TX, ssss Bill, GA, wwww

I would sort by State, tell it I want 2 and skip the entry for Tom which is the 3rd OR state. Ideas?

19 Comments
2024/11/27
16:32 UTC

1

Trying to use PowerShell 7.4 to do tasks with a virtual disk drive

We have a piece of Windows 10 desktop software called TaxDome. One of the functions this program has allows us to have a virtual drive in the windows file explorer.

Screenshot of the virtual drive

https://imgur.com/a/72FXvS3

I am attempting to use Powershell to automate from task like copying a file to this drive, delete some files inside the virtual drive, etc. My issue is that PowerShell is unable to see the virtual drive.

I run this command to see all the drives and it does not list the Z drive.

Get-PSDrive -PSProvider FileSystem

Here is a screenshot of the result with the drive letters

https://imgur.com/a/sNppeHQ

Get-PSDrive

Running this command give me this

https://imgur.com/a/BYDd8Pt

I am looking for some help on what to try next or if what I am attempting to do isn't going to work

The virtual drive only is visible once I sign into my account on the desktop software, and I know it uses the Dokan-dev library for the virtual drive.

https://github.com/dokan-dev/dokany

2 Comments
2024/11/27
16:31 UTC

4

Migrating modular Azure Automation runbooks from PowerShell 5.1 to 7.2

Hi,

im currently trying to migrate our Azure Automation runbooks from 5.1 to 7.2. The runbooks are modular and there are often used functions that are outsourced as an extra RB. The Problem I got so far is that the call of other runbooks is more complicated in 7.2 than 5.1. In 5.1 you can call another runbooks like on a local PC with .\MyRunbook.ps1 but under 7.2 it must be done via Start-azautomationrunbook with parameter. In the past I could return the Output of the function easily to the parent script but in 7.2 return will not work anymore or at least i did not figure out how it works...

I saw that I can get the writen output via Get-AzAutomationJobOutput -AutomationAccountName "ACCOUNTNAME" -Id "JOBID" -ResourceGroupName RESSOURCEGROUP -Stream any

This brings the Problem that I get all the Output in small bites, this means every printed line is a new Hashtable with a summary attribute which contains the written output. This is very much overhad in my opinion.

Has anyone experience with this migration and an idea how I can return Objects to the parent script. In the example below is a function to get all Items from the Graph API and return them. This worked great in 5.1 and I dont want to rewrite all the functions to use them in 7.2.

Thank you for every kind of help

Best regards

Sven

# Sven
# Version 1.0 - 01.10.2022 
# ==================================================================================
# Getting all items from Graph Nextlink 
# Outsourcing of the function Get-NextLink
# ==================================================================================

<#
.SYNOPSIS
Getting @odata.nextlink uri from Graph Api

.DESCRIPTION
This function starts from an uri and gets all elements via 
the nextlink Attribute that is responded from the Graph Api

.PARAMETER Uri
Uri in format Https://Graph.microsoft.com/[APIVERSION]/[RESOURCE]

.OUTPUTS
System.arraylist that contains System.hashtables with attributes.

.EXAMPLE
Get-nextlink -uri https://Graph.microsoft.com/beta/groups
#>

Param
(
    [Parameter(Mandatory = $true)]
    $Uri
)
try
{
    $output=do
    {
        $current = Invoke-MGGraphrequest -uri $Uri 
        $current.value
        $uri = $current."@odata.NextLink" #Get Next Profiles  
    }While($uri -ne $null) 
    return $output
}
catch
{
    return $null
    $exception = $_.Exception
    Write-Output "Exception occured: $($exception)"
    $EmailTo = $errorMailReceiver;
    $Subject = "Azure Automation error in runbook rb_common_function_getnextlink"
    $Body = "Dear colleagues,<br /><br />an exception has occured running the Azure Automation Runbook 'rb_common_function_getnextlink'.<br /><br /> Details:$($exception)<br /><br />Best Regards,<br /><br />Your SCCM Team."
    
    $output = .\rb_common_send_mail_with_graph_powershell.ps1 -EmailTo $EmailTo -Subject $Subject -Body $Body
    Write-Output "Result from mail send script $($output)"
    Write-Output "Job outcome: Runbook_Result:Error_occured"
    throw
}
6 Comments
2024/11/27
11:02 UTC

1

Script cannot be loaded because its content could not be read

Hi,

I'm getting the error below, when running a script remotely (using Intune):

detect.ps1 cannot be loaded because its content could not be read.
+ CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnauthorizedAccess on integration

There seems to be very little reference to this error, at least on Google. Can anyone help in understanding and resolving it?

Thanks!

6 Comments
2024/11/27
08:17 UTC

1

Help with PowerShell script and.csv bulk uploading new users to Microsoft 365

Before I begin Let me say I am a complete novice using PowerShell. The script I'm using has one flaw (or maybe more) it created the new users but does not assign a license. Can you please help and tell where I went wrong. These are my .csv headers These all I need for my project.

|| || |Username|First name|Last Name|Display Name|Department|Type of Microsoft 365 license|

This the script:

# Import the CSV file

$users = Import-Csv -Path "C:\temp\Multi_Site_User_Creation_Microsoft.csv"

# Loop through each user in the CSV file

foreach ($user in $users) {

# Create a new user in Microsoft 365

$passwordProfile = @{

Password = "S@ntaClaus2025"

ForceChangePasswordNextSignIn = $true

}

$newUser = New-MgUser -UserPrincipalName $user.Username `

-GivenName $user."First name" `

-Surname $user."Last Name" `

-DisplayName $user."Display Name" `

-Department $user.Department `

-UsageLocation "US" `

-PasswordProfile $passwordProfile `

-MailNickname $user.Username.Split('@')[0] `

-AccountEnabled

# Check if the user was created successfully

if ($newUser -ne $null) {

# Create an AssignedLicense object

$assignedLicense = [Microsoft.Graph.PowerShell.Models.IMicrosoftGraphAssignedLicense]::new()

$assignedLicense.SkuId = $user.'Type of Microsoft 365 license'

# Assign the license to the new user

Set-MgUserLicense -UserId $newUser.Id -AddLicenses @($assignedLicense) -RemoveLicenses @()

} else {

Write-Host "Failed to create user: $($user.Username)"

}

}

Thanks in Advance.

17 Comments
2024/11/27
03:05 UTC

0

Using nested loops for checking wildcard paths in registry

I want to be able to check the values on this particular path in registry:

"REGISTRY::HKEY_USERS\S-1-5-21*\Software\Google\Chrome\PreferenceMACs\*\extensions.settings\"

As you can see, I have wildcards for S-1-5-21* and another * right after PreferenceMACs. But now I'm stuck on how I could put the second wildcard values into variables.

Ultimately, my goal is to basically check every user profiles and see if a particular extension exists. Those extension IDs can be found under "extensions.settings" folder.

Here's what I've done so far:

$chromepath1s = Get-ChildItem "REGISTRY::HKEY_USERS"

$chromepath2s = "\Software\Google\Chrome\PreferenceMACs"

$chromepath8s = "\extensions.settings\"

ForEach ($chromepath1 in $chromepath1s) {

$chromepath3s = Join-Path -Path $chromepath1 -ChildPath $chromepath2s

foreach ($chromepath3 in $chromepath3s) {

#Write-Host $chromepath3

foreach ($chromepath4 in $chromepath3) {

#Write-Host $chromepath4

foreach ($chromepath5 in $chromepath4) {

Write-Host "REGISTRY::$chromepath5"

}} }}

Can someone help me continue this script? Appreciate the help on this one.

5 Comments
2024/11/26
21:15 UTC

Back To Top