windows
98 TopicsWindows 10 Subscription Activation via Powershell
We recently purchased E3 Subscription licenses for Windows 10. Microsoft's documentation states for exisiting enterprise deployments, the following script should be ran via a command line: @echo off FOR /F "skip=1" %%A IN ('wmic path SoftwareLicensingService get OA3xOriginalProductKey') DO ( SET "ProductKey=%%A" goto InstallKey ) :InstallKey IF [%ProductKey%]==[] ( echo No key present ) ELSE ( echo Installing %ProductKey% changepk.exe /ProductKey %ProductKey% ) I'm attempting to re-write this in powershell so we can use it as a remediation step in a configuration baseline in SCCM. Below is the powershell script I wrote: $ProductKey = (Get-CimInstance -ClassName SoftwareLicensingService).OA3xOriginalProductKey if ($ProductKey){ start-process c:\Windows\System32\changePK.exe -ArgumentList "/ProductKey $ProductKey" } The script runs without error, but it's not actually completing the intended task (activating the embedded windows 10 pro key). I'm not sure where I'm going wrong. I'm pretty new to powershell so any assistance would be greatly appreciated.42KViews1like8CommentsCheck if user already exists
Hi there, I'm trying to create a script which basically requires the user's input, so they'll need to enter their first name & last name and AD will check if that AD account already exists for the user or not, if it does then it would say '_____ already exists' and stops the script going any further as it's currently doing for any users whether or not they exist - below. What's the correct commands I should be using as below so it will search AD for that user and if they don't exist it would say 'User doesn't exist' and continue with the rest of the script which then asks for the user's dept and phone number etc, as currently it's just saying all the user's already exist and stops the script, I've tried various recommended commands from other forums. Thank you in advance37KViews0likes1CommentSecure Way to store lots of credentials using powershell
Dear Community I wanted to ask if there is any way I can store lots of creedentials while still being able to use them in Powershell? I dont want to enter anything in a popup window, because there are way to many credentials to to that by hand. Is it possible that I can just put them in some kind of file and then get the wanted informations (while the file or its contents are somehow encrypted)? Thanks in advance MartinSolved21KViews0likes5CommentsNew-SMBMapping not showing in Explorer until Explorer process is closed/restarted
I'm writing a script to remap drives to new paths (file server migration), and I had everything working. I'm using Remove-SMBMapping and New-SMBMapping. While it was working there was a strange bug where it would only work if I pasted the code directly into powershell. But if I called the .ps1 script file, the drive mappings would change (as verified by NET USE from the command line), Explorer continued to show and use the old drive mappings. If I end process for Explorer.exe and re-run it, then it would show and use the new mappings. I just ignored this at the time. Well now I'm doing some more testing, now no matter what I do, when using New-SMBMapping in any way, Explorer refuses to see the drive (even new mappings) while the system does see the correct drives via cmdline. I'm at a complete loss as to why this is an issue. It occurs in both Powershell 7 as well as Windows Powershell 5.1. Does anyone have a clue as to what is happening here? FWIW I know that drives mapped in the standard UAC user context are not visible to admin contexts and vice versa. That is not the issue here. This is all under the same user context. No elevated admin sessions are at play. In fact, if it were this, restarting Explorer would have no affect. Also this is an issue whether -persistent $true is used or not. Finally, if I just simply use native Windows cmd prompt command "Net Use" to map the drive, even within the Powershell console, everything works as expected. This is only an issue using the powershell specific cmdlet to map the drive.19KViews0likes16CommentsWhat is this log happening in PowerShell/operational?
Hi I’m not too sure if this is the right place to ask but since it’s happening in the PowerShell/operational log every month, I thought it’d be good to post here. I just want to know if I’m in any danger or if I’m safe and I’m just being paranoid. Task Category: Execute a remote command Creating Scriptblock text (1 of 1): # Copyright © 2008, Microsoft Corporation. All rights reserved. #Common utility functions Import-LocalizedData -BindingVariable localizationString -FileName CL_LocalizationData # Function to get user troubleshooting history function Get-UserTSHistoryPath { return "${env:localappdata}\diagnostics" } # Function to get admin troubleshooting history function Get-AdminTSHistoryPath { return "${env:localappdata}\elevateddiagnostics" } # Function to get user report folder path function Get-UserReportPath { return "${env:localappdata}\Microsoft\Windows\WER\ReportQueue" } # Function to get system report folder path function Get-MachineReportPath { return "${env:AllUsersProfile}\Microsoft\Windows\WER\ReportQueue" } # Function to get threshold to check whether a folder is old function Get-ThresholdForCheckOlderFile { [int]$threshold = -1 return $threshold } # Function to get threshold for deleting WER folder function Get-ThresholdForFileDeleting() { [string]$registryEntryPath = "HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" [string]$registryEntryName = "PurgeThreshholdValueInKB" [double]$defaultValue = 10.0 return Get-RegistryValue $registryEntryPath $registryEntryName $defaultValue } # Function to get the size of a directory in kb function Get-FolderSize([string]$folder = $(throw "No folder is specified")) { if([String]::IsNullOrEmpty($folder) -or (-not(Test-Path $folder))) { return 0 } if(-not $Global:DirectoryObject) { $Global:DirectoryObject = New-Object -comobject "Scripting.FileSystemObject" } return ($Global:DirectoryObject.GetFolder($folder).Size) / 1kb } # Function to delete a folder function Delete-Folder([string]$folder = $(throw "No folder is specified")) { if([String]::IsNullOrEmpty($folder) -or (-not(Test-Path $folder))) { return } Remove-Item -literalPath $folder -Recurse -Force } # Function to delete old folders function Delete-OldFolders($folder=$(throw "No folder is specified")) { if(($folder -eq $null) -or (-not(Test-Path $folder))) { return } [int]$threshold = Get-ThresholdForCheckOlderFile $folders = Get-ChildItem -LiteralPath ($folder.FullName) -Force | Where-Object {$_.PSIsContainer} if($folders -ne $null) { foreach($folder in $folders) { if((($folder.CreationTime).CompareTo((Get-Date).AddMonths($threshold))) -lt 0) { Delete-Folder ($folder.FullName) } else { Delete-OldFolders (Get-Item ($folder.FullName)) } } } } # Function to get registry value function Get-RegistryValue([string]$registryEntryPath = $(throw "No registry entry path is specified"), [string]$registryEntryName = $(throw "No registry entry name is specified"), [double]$defaultValue = 0.0) { [double]$registryEntryValue = $defaultValue $registryEntry = Get-ItemProperty -Path $registryEntryPath -Name $registryEntryName if($registryEntry -ne $null) { $registryEntryValue = $registryEntry.$registryEntryName } return $registryEntryValue } # Function to get the percentage that WER queue can take up function Get-Percentage() { [string]$registryEntryPath = "HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting" [string]$registryEntryName = "MaxQueueSizePercentage" [double]$defaultValue = 100.0 return Get-RegistryValue $registryEntryPath $registryEntryName $defaultValue } # Function to get free disk space on machine function Get-FreeSpace { [double]$freeSpace = 0.0 [string]$wql = "SELECT * FROM Win32_LogicalDisk WHERE MediaType=12" $drives = Get-WmiObject -query $wql if($null -ne $drives) { foreach($drive in $drives) { $freeSpace += ($drive.freeSpace) } } return ($freeSpace / 1KB) } # Function to get all unnecessary files function Get-UnnecessaryFiles([string]$folder = $(throw "No folder is specified")) { if([String]::IsNullOrEmpty($folder) -or (-not(Test-Path $folder))) { return $null } [int]$threshold = Get-ThresholdForCheckOlderFile return (Get-ChildItem -literalPath $folder -Recurse -Force | Where-Object {($_.PSIsContainer) -and ((($_.CreationTime).CompareTo((Get-Date).AddMonths($threshold))) -lt 0)}) } # Function to format disk space (KB -> MB) function Format-DiskSpaceMB([double]$space = $(throw "No space is specified")) { return [string]([Math]::Round(($space / 1KB), 3)) } # Function to format disk space (B -> GB) Function Format-DiskSpaceGB([double]$space = $(throw "No space is specified")) { return [string]([Math]::Round(($space / 1GB), 3)) } # Function to attach item to the list with delimiter "/" function AttachTo-List([string]$list = $(throw "No list is specified"), [string]$item = $(throw "No item is specified")) { if([String]::IsNullOrEmpty($list)) { return $item } if([String]::IsNullOrEmpty($item)) { return $list } return $list + "/" + $item } # Function to parse the the list with delimiter "/" function Parse-List([string]$list = $(throw "No list is specified")) { if($list -eq $null) { return $null } return $list.Split("/", [StringSplitOptions]::RemoveEmptyEntries) } # Function to get list length function Get-ListLength([string]$list = $(throw "No list is specified")) { if($list -eq $null) { return 0 } $result = Parse-List $list if($result -is [string]) { return 1 } elseif($result -is [object[]]) { return $result.count } else { return 0 } } # Function to convert to WQL path function ConvertTo-WQLPath([string]$wqlPath = $(throw "No WQL path is specified")) { if($wqlPath -eq $null) { return "" } return $wqlPath.Replace("\", "\\") } # Function to check whether the shortcut is valid function Test-ValidLink([Wmi]$wmiLinkFile = $(throw "No WMI link file is specified")) { if(($wmiLinkFile -eq $null) -or ([String]::IsNullOrEmpty($wmiLinkFile.Target))) { return $false } return Test-Path $wmiLinkFile.Target } # Function to chech whether have permission to delete the shortcut file function Test-Delete([Wmi]$wmiLinkFile = $(throw "No WMI link file is specified")) { if($wmiLinkFile -eq $null) { return $false } return ($wmiLinkFile.AccessMask -band 0x10000) -eq 0x10000 } # Function to get desktop path function Get-DesktopPath() { $methodDefinition = @" public static string GetDesktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } } "@ $type = Add-Type -MemberDefinition $methodDefinition -Name "DesktopPath" -PassThru return $type::GetDesktopPath } # Function to get startup path function Get-StartupPath() { $methodDefinition = @" public static string GetStartupPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } } "@ $type = Add-Type -MemberDefinition $methodDefinition -Name "StartupPath" -PassThru return $type::GetStartupPath } # Function to remove all files in the list function Remove-FileList([string]$list = $(throw "No list is specified")) { if([String]::IsNullOrEmpty($list)) { return } try { Parse-List $list | Foreach-Object { if(-not([String]::IsNullOrEmpty($_))) { Remove-Item $_ -Force } } } catch { $_ | ConvertTo-Xml | Update-DiagReport -id DeleteFileExceptions -Name $localizationString.filesFailToRemove_name -Description $localizationString.filesFailToRemove_description -Verbosity Warning } } # Function to get the last access time of an Icon function Get-LastAccessTime([string]$filePath = $(throw "No file path is specified")) { if([String]::IsNullOrEmpty($filePath) -or -not(Test-Path $filePath)) { throw "No file path found" } $typeDefinition = @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; using ComType = System.Runtime.InteropServices.ComTypes; public sealed class FileInfo { private FileInfo() { } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct UAINFO { internal int cbSize; internal int dwMask; internal float R; internal uint cLaunches; internal uint cSwitches; internal int dwTime; internal ComType.FILETIME ftExecute; [MarshalAs(UnmanagedType.Bool)] internal bool fExcludeFromMFU; internal UAINFO(int dwMask) { this.cbSize = Marshal.SizeOf(typeof(UAINFO)); this.dwMask = dwMask; this.R = 0; this.cLaunches = 0; this.cSwitches = 0; this.dwTime = 0; this.ftExecute = new ComType.FILETIME(); this.fExcludeFromMFU = false; } } internal const int UAIM_FILETIME = 1; internal static Guid UAIID_SHORTCUTS = new Guid("F4E57C4B-2036-45F0-A9AB-443BCFE33D9F"); [ComImport, Guid("90D75131-43A6-4664-9AF8-DCCEB85A7462"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IShellUserAssist { int FireEvent(ref Guid pguidGrp, int eCmd, string pszPath, int dwTimeElapsed); int QueryEntry(ref Guid pguidGrp, string pszPath, ref UAINFO pui); int SetEntry(ref Guid pguidGrp, string pszPath, ref UAINFO pui); int RenameEntry(ref Guid pguidGrp, string pszFrom, string pszTo); int DeleteEntry(ref Guid pguidGrp, string pszPath); int Enable(bool fEnable); } [ComImport, Guid("DD313E04-FEFF-11d1-8ECD-0000F87A470C")] internal class UserAssist { } public static DateTime GetLastAccessTime(string filePath) { if(String.IsNullOrEmpty(filePath)) { throw new ArgumentException("The file path is null or empty"); } UAINFO uaInfo = new UAINFO(UAIM_FILETIME); IShellUserAssist iShellUserAssist = new UserAssist() as IShellUserAssist; if (iShellUserAssist == null) { throw new InvalidOperationException("Can't get iShellUserAssist interface"); } try { Marshal.ThrowExceptionForHR(iShellUserAssist.QueryEntry(ref UAIID_SHORTCUTS, filePath, ref uaInfo)); } catch { throw new InvalidOperationException("Can't query info about" + filePath); } long fileTime = (((long)uaInfo.ftExecute.dwHighDateTime) << 32) + uaInfo.ftExecute.dwLowDateTime; return DateTime.FromFileTime(fileTime); } } "@ $type = Add-Type -TypeDefinition $typeDefinition -PassThru return $type[0]::GetLastAccessTime($filePath) } # Function to check whether the icon is pointing to a file function Test-FileShortcut([Wmi]$wmiLinkFile = $(throw "No wmi link file is specified")) { if($wmiLinkFile -eq $null) { return $false } [string]$target = $wmiLinkFile.Target if([String]::IsNullOrEmpty($target) -or -not(Test-Path $target)) { return $false } return -not((Get-Item $target).PSIsContainer) } # Function to create a choice in interaction page function Get-Choice([string]$name = $(throw "No choice name is specified"), [string]$description = $(throw "No choice description is specified"), [string]$value = $(throw "No choice value is specified"), [xml]$extension) { return @{"Name"=$name;"Description"=$description;"Value"=$value;"ExtensionPoint"=$extension.InnerXml} } # Function to check whether the current machine is domain joined Function Test-DomainJoined() { return (Get-WmiObject -query "select * from win32_ntdomain where Status ='OK'") -ne $null } # Function to update time source Function Update-TimeSource([string]$timeSource = $(throw "No time source is specified")) { w32tm.exe /config /update /manualpeerlist:"$timeSource" } # Function to get system drive info function Get-SystemDriveInfo() { [string]$wql = "SELECT * FROM Win32_LogicalDisk WHERE MediaType=12 AND Name = '" + ${env:systemdrive} + "'" return Get-WmiObject -query $wql } # Function to get time service status function Get-ServiceStatus([string]$serviceName=$(throw "No service name is specified")) { [bool]$startService = $true [WMI]$timeService = @(Get-WmiObject -Query "Select * From Win32_Service Where Name = `"$serviceName`"")[0] if($null -ne $timeService) { [ServiceProcess.ServiceControllerStatus]$timeServicesStatus = (Get-Service $serviceName).Status if(([ServiceProcess.ServiceControllerStatus]::Stopped -eq $timeServicesStatus) -or ([ServiceProcess.ServiceControllerStatus]::StopPending -eq $timeServicesStatus)) { $startService = $false } } return $startService } # Function to wait for expected service status function WaitFor-ServiceStatus([string]$serviceName=$(throw "No service name is specified"), [ServiceProcess.ServiceControllerStatus]$serviceStatus=$(throw "No service status is specified")) { [ServiceProcess.ServiceController]$sc = New-Object "ServiceProcess.ServiceController" $serviceName [TimeSpan]$timeOut = New-Object TimeSpan(0,0,0,5,0) $sc.WaitForStatus($serviceStatus, $timeOut) } ScriptBlock ID: 13e9b2e8-1cbb-4279-b694-6ef6c113bd47 Path: C:\WINDOWS\TEMP\SDIAG-8719f62f-f3f5-4383-a522-c77b8213468e\CL_Utility.ps1Solved15KViews0likes3CommentsBatch file: filename with ampersand (&)
Hello, I have a simple bat file named "test&.bat" with this content: @echo off echo This is test.bat pause When I use "Run as administrator" on the file, the pause command is not handled. When I double-click on the file, it works. When I rename the file as "test.bat", it works even with "Run as administrator". Do you have any idea why the ampersand character causes troubles with "Run as administrator"?Solved15KViews1like4CommentsError message when running Update-Module
I'm receiving the following error message when running Update-Module. Any views on how I can fix this? Update-Module : The 'Update-Module' command was found in the module 'PowerShellGet', but the module could not be loaded. For more information, run 'Import-Module PowerShellGet'. At line:1 char:1 + Update-Module -Name MicrosoftPowerBIMgmt + ~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Update-Module:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule When I run the suggested follow-up I get this: Import-Module : The cloud file provider is not running. At line:1 char:1 + Import-Module PowerShellGet + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Import-Module], CommandNotFoundException + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand Many thanksSolved11KViews0likes2CommentsWhy does my generated JSON have too many "\\"?
Dear Community I have a Powershell Script which generates a JSON file with data in it. I have a problem with this file though. It generates double the amount of "\\"! Do you know how I could solve this? Here is my Code to generate the JSON File: [ordered]@{ pcname='ENTER HERE'; share='\\ENTER HERE\C$'; filename='ENTER HERE'; destfilepath='some\folder'; destfile='$in.share\$in.destfilepath\$in.filename'; RDdestfile='C:\$in.destfilepath\'; Username="ENTER HERE"; Password="ENTER HERE"; EncryptedPassword="" } | ConvertTo-Json | Out-File "$secFile" $secFile is just a path to save the file to. Just tell me if you need this too. The output JSON file looks liek this though: { "pcname": "ENTER HERE", "share": "\\\\ENTER HERE\\C$", "filename": "ENTER HERE", "destfilepath": "some\\folder", "destfile": "$in.share\\$in.destfilepath\\$in.filename", "RDdestfile": "C:\\$in.destfilepath\\", "Username": "ENTER HERE", "Password": "ENTER HERE", "EncryptedPassword": "" } Greetings Martin Edit: I also posted this question in the PowerShell.org Forum and Stackoverflow, just so you know https://powershell.org/forums/topic/why-does-my-generated-json-have-too-many/ https://stackoverflow.com/questions/63446524/why-does-my-generated-json-have-too-manySolved8.8KViews0likes2CommentsIntegrating WSL with Windows 7 64bit with Power Shell
Hello Microsoft Community! This is my first post. I am trying to get WSL 1.0 to function with windows 7. For some reason, I get errors in Power Shell when trying to run the script to enable WSL. I have found information that says that dism.exe has two versions, one version for 32 bit and one version for 64 bit. I have tried the script for both file locations as the locations are supposed to designate which version of the .exe gets used. Within Power Shell, the error is the same. I cannot service a 64 bit system with the 32 bit operation. There are log files for both attempts, I have yet to inspect both of the log files to see if the information is the same. I have very minimal experience with scripting or interpreting the information within the log files. I am trying to get FreeCAD to run on Windows 7 64 bit. It worked with windows 10, but WSL is a part of windows 10 as a windows feature that can just be activated with an option. With this PC, I have windows 7 and cannot currently upgrade to Windows 10 or 11. Does anyone have any idea how I can get Windows 7 to support my App?Solved8.4KViews0likes2CommentsA simple example of Windows PowerShell Just Enough Administration (JEA)!
Dear Microsoft and PowerShell Friends, Using PowerShell to establish a remote connection and then manage, for example, a domain controller or any other server that is a member of the domain, is really fun. But what about security? When I as a domain administrator establish a remote connection, I have a huge number of cmdlets at my disposal. #We start a "normal" remote connection and check how many cmdlets are available Enter-PSSession -ComputerName dc01 (Get-Command).count Maybe you (the administrator) do not always want to establish the remote connection to a specific server to process an existing task, but you would like to delegate this step to another person. But only in a way that this person cannot work with too many cmdlets. That's where PowerShell Just Enough Administration (JEA) comes in. With this technique you can, for example, provide a specific Active Directory group with exactly the number of cmdlets to perform the necessary work on the desired server. JEA is best suited for tasks that are clearly defined. JEA is not suitable for troubleshooting or research. The best place to start is in Active Directory: 1. Create a security group with the name Helpdesk in AD. 2. Add a user (or users) to the group After that we switch to the PowerShell ISE (on the server where you want to make the cmdlets available) or the one you trust (maybe VSCode ;-). #Are comments! #We navigate in to the following path Set-Location 'C:\Program Files\WindowsPowerShell\Modules' #Create a new directory New-Item -ItemType Directory Helpdesk #Navigate to the directory Set-Location Helpdesk #Create a new directory New-Item -ItemType Directory RoleCapabilities #Navigate to the directory Set-Location RoleCapabilities #Creates a file that defines a set of capabilities to be exposed through a session configuration New-PSRoleCapabilityFile -Path .\Helpdesk.psrc #Now we edit this file ISE .\Helpdesk.psrc In this file you can specify among others cmdlets, functions and also commands that can be used. In this example I provide "Get-Service" and "whoami". In a practical example, you would provide all the necessary commands/cmdlets needed for the specific task (just as the case may be). #Creates a file that defines a session configuration New-PSSessionConfigurationFile .\Helpdesk.pssc #Now we edit this file ISE .\Helpdesk.pssc In this file, you can specify the session configuration, a virtual administrator account, and user roles, among other things. #Let us check the settings Test-PSSessionConfigurationFile .\Helpdesk.pssc #Creates and registers a new session configuration Register-PSSessionConfiguration -Name Helpdesk -Path .\Helpdesk.pssc #We need to restart the WinRM Service Restart-Service WinRM #Gets the registered session configurations on the computer Get-PSSessionConfiguration Now switch to the system from which you want to establish a remote session. #We establish a connection Enter-PSSession -ComputerName dc01 -ConfigurationName Helpdesk -Credential grid\james.west #And check the number of cmdlets and the account created for the connection Get-Command We now have exactly the cmdlet and the command we specified. We also see that the session was established with a virtual account. This means that these credentials are not saved after the session ends. #Close the Session Exit-PSSession Back to the server. #(Optional) Deletes registered session configurations from the computer Unregister-PSSessionConfiguration -Name Helpdesk Clearly, that was not super spectacular or fancy. But I still wanted to share my experience with you. Thank you for taking the time to read this article. Kind regards, Tom Wechsler P.S. All scripts (#PowerShell, Azure CLI, #Terraform, #ARM) that I use can be found on github! https://github.com/tomwechsler7.9KViews4likes0Comments