@Windows PowerShell
44 TopicsExport 365 Users last logon time using powershell
I have created a PowerShell command that is supposed to export every users last logon time that is greater than 1 day. But it continues to create a blank document. Below is the command. Get-Mailbox -RecipientType 'UserMailbox' |%{ Get-MailboxStatistics $_.UserPrincipalName | Sort-Object LastLogonTime | Where {$_.LastLogonTime -lt ([System.DateTime]::Now).AddDays(-1) } | Export-Csv "C:\Logs\O365MAILBOXSTATS_REPORT1.CSV" -NoTypeInformation -Append}13KViews0likes2CommentsDownload and Install Windows Updates offline using the wsusscn2.cab file and Windows Update API
Hi, I'm trying to find a way to install Windows Updates (CAB files) on offline Windows 10 V1809 computers. Overall the process I'm trying to automate is: 1. Scan for missing Windows Updates on the computer and download all missing Windows Updates 2. On an offline computer - install the Updates. I'm using the wsusscn2.cab file as described here: https://learn.microsoft.com/en-us/windows/win32/wua_sdk/using-wua-to-scan-for-updates-offline to search the updates, download them, and then try to install them. I manage to search and download the updates, but I encounter this error when trying to install: When -2145124318 in Hex is: 0x80240022 This error code = WU_E_ALL_UPDATES_FAILED Operation failed for all the updates. How can I fix my code to successfully install this updates? Here is the code I'm using: #Search for Windows Updates: # Load the Windows Update Agent COM object $UpdateSession = New-Object -ComObject Microsoft.Update.Session $UpdateServiceManager = New-Object -ComObject Microsoft.Update.ServiceManager #Load the wsusscn2.cab file that enables offline Updates instllation: $UpdateService = $UpdateServiceManager.AddScanPackageService("Offline Sync Service", "c:\wsusscn2.cab") # Create a searcher for available updates $UpdateSearcher = $UpdateSession.CreateUpdateSearcher() # Search for updates in the SoftwareDistribution folder: #The ServerSelection enumeration defines values that describe the type of server to use for an update search operation. # ssOthers: Search another server, to be specified by other means $updateSearcher.ServerSelection = 3 # ssOthers $UpdateSearcher.ServiceID = $UpdateService.ServiceID $Criteria = "IsInstalled=0 and Type='Software'" $SearchResult = $UpdateSearcher.Search($Criteria) $Updates = $SearchResult.Updates if ($SearchResult.Updates.Count -eq 0) { write-Host "There are no applicable updates" } #Download the Windows Updates (to SoftwareDistribution): $SearchResult = $Updates # Create a Windows Update Session $Session = New-Object -ComObject Microsoft.Update.Session # Create a Windows Update Downloader: $Downloader = $Session.CreateUpdateDownloader() $Downloader.Updates = $SearchResult #Download updates to C:\Windows\SoftwareDistribution $Downloader.Download() #Install the Windows Updates from SoftwareDistribution: # Create the Installer Object: $installer = New-Object -ComObject Microsoft.Update.Installer $Installer.Updates = $Updates #Install updates: $Result = $Installer.Install() Thanks, Ann10KViews0likes0CommentsSet-ACL "Attempted to Perform an Unauthorized Operation"
Hi Folks, I'm currently working on automating security changes on Azure File Shares. As part of this process, I'd like to use Get-ACL and Set-ACL as the easiest ways to copy over a base set of permissions - icacls doesn't have as good functionality for this as it only allows restoring permissions to a file of the same name. However, whenever I use Set-ACL, I immediately get: Set-Acl : Attempted to perform an unauthorized operation. At line:1 char:55 + ... ath | Set-Acl -Path $concatPath + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: () [Set-Acl], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetAclCommand As a note I have removed path names. The account I'm using is a domain admin and has NTFS permission to the file. It can edit these permissions using the GUI with no issues. It also has an Elevated Contributor role in Azure AD, so it should be able to edit these ACLs. I've also tried the NTFSSecurity module, which has the same issues. Similarly, I have tried to mount the fileshare to a drive with New-PSDrive, in case that helped, but no luck there either. I'm pretty out of ideas here, and icacls will require a lot more logic work to strip back the inherited permissions to what I want them to be. If anyone has any other ideas, I'd love to hear them. Thanks in advance!9KViews0likes6CommentsGet-AzureADUserManager : Cannot bind argument to parameter 'ObjectId' because it is null.
Hi All, I am trying to fetch the Manager's Manager using the "Get-AzureADUserManager" function by passing ObjectId of manager. However while passing the manager's object to get his/her manager , getting an error below : Please help at the earliest. Code : foreach($user in $users) { $row = $Datatable.NewRow() $manager=Get-AzureADUserManager -ObjectId $user.ObjectId $seniorM=Get-AzureADUserManager -ObjectId $manager.ObjectId $row.Name=$user.GivenName $row.Surname=$user.Surname $row.manager=$manager.DisplayName $row.seniorM=$seniorM.DisplayName $Datatable.Rows.Add($row) } Error Message : Get-AzureADUserManager : Cannot bind argument to parameter 'ObjectId' because it is null. At line:29 char:43 + $seniorM=Get-AzureADUserManager -ObjectId $manager.ObjectId + ~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Get-AzureADUserManager], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Open.AzureAD16.PowerShell.GetUserManagerSolved8.7KViews0likes2CommentsShould I delete Windows Terminal or Administrator: Powershell?
I have had a major problem with hackers and cyber stalking for nearly a year. I just had the hard drive replaced for the second time in five months on my Dell Inspiron 7706 because of this. Today I discovered that my hacker has created a spoofed PowerShell Administrator ID, which allows her (them) to remotely access my laptop and insert viruses. Can I safely delete the "Administrator: PowerShell" or Windows Terminal without damaging my new hard drive? Thank you. @Windows PowerShell8KViews0likes2CommentsGet users from CSV, foreach user, get country, name, etc., then Export
Hi! I have a problem with PS query. I have a CSV file with +1000 userprincipalname. Id like to export that UPN and for each user get info like userprincipalname, title, country, department, enabled, then export to excel. My example queries: $csv = gc "C:\New folder\Users.csv" $Users=@() $csv | Foreach{ $elements=$_ -split(";") $Users+= ,@($elements[0]) } ForEach ($User in $Users) { Get-ADUser -filter "userPrincipalName -eq '$User'" -Properties * | Select-Object userprincipalname, title, country, department, enabled } OR $Users = Get-contect -path "C:\New folder\Users.csv" ForEach ($User in $Users) { Get-ADUser -filter "userPrincipalName -eq '$User'" -Properties * | Select-Object userprincipalname, title, country, department, enabled } OR $Users = Get-contect -path "C:\New folder\Users.csv" ForEach ($User in $Users) { Get-ADUser -filter $User -Properties * | Select-Object userprincipalname, title, country, department, enabled } My excel has UPN only, like: mailto:email address removed for privacy reasons mailto:email address removed for privacy reasons etc. No headers. Someone will help? 😞7.5KViews0likes2CommentsOlder versions of Teams are still appearing in the registry for other user profiles and are being fl
Hello, I wanted to update you on the issues we are facing after cleaning Classic Teams. Older versions of Teams are still appearing in the registry for other user profiles and are being flagged as vulnerable in 365 Defender, specifically in the HKEY_USERS registry path for others users. For example, as evidence from the Defender portal, here are some entries indicating software issues: - Endpoint Name: TestPC - Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\Teams - HKEY_USERS\user1\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Teams - HKEY_USERS\user2\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Teams - HKEY_USERS\user3\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Teams We attempted to remove the registry entries from other user profiles to clean up the Classic Teams presence by using the following commands: powershell       " reg load "hku\$user" "C:\Users\$user\NTUSER.DAT"       " Test-Path -Path Registry::HKEY_USERS\$hiveName\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Teams " For checking the registry presence, we used the detection and remediation method in Intune for cleaning Classic Teams. I ran the detection script on only three PCs for testing. Surprisingly, we received a warning from Sentinel about "User and group membership reconnaissance (SAMR) on one endpoint," indicating a potential security incident involving suspicious SAMR (Security Account Manager Remote) queries. This was detected for admin accounts, DC, and also for an account belonging to someone who left the organization five years ago (ABC Admin). I am looking for appreciate your guidance on the best practices for detecting and removing Classic Teams leftovers in the registry for other user profiles. Best Practice: - How to detect and remove Classic Teams registry entries for other user profiles in the system. - Best method? Using the Hive to load another user profile into the registry and remove the Classic Teams registry entries. Reference Links: - [Older versions of Teams showing in user profiles](https://answers.microsoft.com/en-us/msteams/forum/all/older-versions-of-teams-showing-in-user-profiles/2bc7563c-ccc9-4afc-b522-337acff9d20e?page=1) - [Remove old user profiles on Microsoft Teams (Reddit)](https://www.reddit.com/r/PowerShell/comments/1bvjner/remove_old_user_profiles_on_microsoft_teams/)6.3KViews0likes3CommentsApp installation with PowerShell and winget
Hello, I'm trying to install a Visual C++ Redistributable package with winget. The first problem I had was that "App Installer" wasn't installed on the devices so I installed it via the "Add-AppxPackage" command. For some Intune showed me that the script had failed but it still was installed and I could use winget. After that, I created a new script to install VC redist with winget but it failed. In logs, I found the error message and it says that the term "winget" is not recognized as the name of the cmdlet. Has someone an idea what the problem is?5.6KViews0likes3CommentsPowershell script to add new Network Location for multiple storage volumes?
Hello, Under the "Network Locations" section within "This PC", it is possible to add an infinite(?) amount of network locations using the Add Network Location Wizard. I'm having trouble finding a Powershell script that accomplishes the same thing as this wizard. At my workplace, all 26 drive letters are full and we would like to switch over to network locations to have easy access to more storage volumes. We will need the location to show within the "Network Locations" section within "This PC" and to appear in the left hand column under "This PC", similar to how mounted drives display this way. Thanks!4.7KViews0likes3CommentsHelp with Watcher
Hey guys, some of you can help me to check what is wrong with this script? thank you in advance! # Cartella da monitorare (stessa cartella) $cartellaDaMonitorare = "C:\TEST" # Crea un registro per i file già rinominati $registroFileRinominati = "C:\TEST\registro.txt" # Funzione per rinominare i file MSG con data e ora function Rinomina-FileMSG { param ( [string]$file ) if ($file -match "\.msg$" -and -not $registroFileRinominati.ContainsKey($file)) { $now = Get-Date -Format "yyyyMMddHHmm" $nomeFile = [System.IO.Path]::GetFileNameWithoutExtension($file) $estensione = [System.IO.Path]::GetExtension($file) $nuovoNome = "${now}_${nomeFile}${estensione}" Rename-Item -Path $file -NewName $nuovoNome Write-Host "Rinominato $file in $nuovoNome" $registroFileRinominati[$file] = $true } } # Crea un oggetto FileSystemWatcher per monitorare la cartella $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = $cartellaDaMonitorare $watcher.Filter = "*.msg" $watcher.IncludeSubdirectories = $true $watcher.EnableRaisingEvents = $true # Azione da intraprendere quando viene rilevato un nuovo file $action = { $changeType = $Event.SourceEventArgs.ChangeType $file = $Event.SourceEventArgs.FullPath if ($changeType -eq "Created" -or $changeType -eq "Renamed") { Rinomina-FileMSG -file $file } } # Associa l'azione all'evento Created e Renamed Register-ObjectEvent -InputObject $watcher -EventName Created -Action $action Register-ObjectEvent -InputObject $watcher -EventName Renamed -Action $action # Attendi che lo script venga interrotto Write-Host "Waiting for new MSG files..." while ($true) { Start-Sleep -Seconds 30 }Solved4.1KViews0likes28Comments