I'm trying to activate Windows 10 with PowerShell.
I got the following script:
$computerName = $env:COMPUTERNAME
$key = "[Windows 10 product key is in here]"
$activationService = Get-WmiObject -Query "select * from SoftwareLicensingService" -ComputerName $computerName
$activationService.InstallProductKey($key)
$activationService.RefreshLicenseStatus()
But I keep getting the following exception:
Exception calling "InstallProductKey" : ""
At F:test.ps1:4:1
+ $activationService.InstallProductKey($key)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
I just can't seem to get this right.
The syntax is correct!
I used the following to activate my notebook
$computer = gc env:computername
$key = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
$service = get-wmiObject -query "select * from SoftwareLicensingService" -computername $computer
$service.InstallProductKey($key)
$service.RefreshLicenseStatus()
Launch cmd as Administrator and run:
slmgr.vbs /ipk xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
Related
I followed the Scripting Guy instructions from Microsoft but even with this I still get the same error Scripting Guy article
here is my script:
$p2=Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan -Filter "ElementName = 'Balanced'"
Invoke-CimMethod -InputObject $p2-MethodName Activate
which results in:
Invoke-CimMethod : This method is not implemented in any class
At line:1 char:1
+ Invoke-CimMethod -InputObject $p2 -MethodName Activate
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (Win32_PowerPlan...2-f694-41f0...):CimInstance) [Invoke-CimMethod], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041055,Microsoft.Management.Infrastructure.CimCmdlets.InvokeCimMethodCommand
I cant seem to find answers I have looked in a few locations, I have seen people start to run into this a few months ago but I could not find an answer any advice would be appreciated
my end goal is to write a script where I import a powerplan and then activate it I have the import part working fine it just this last bit. $p contains my imported plan I used $p2 on a default plan for testing purposes.
cheers and thank you in advance for any advice you can offer
I found this code for changing the Power Schema.
Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan | select ElementName, IsActive | ft -a
$p = gwmi -NS root\cimv2\power -Class win32_PowerPlan -Filter "ElementName ='Ultimate Performance'"
$p.Activate()
Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan | select ElementName, IsActive | ft -a
pause
It works on most flavors of Windows O/S. I get this error sometimes.
"Exception calling "Activate" : "This method is not implemented in any class " At line:1 char:1 + $p2.Activate() + ~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WMIMethodException –"
I have a problem with WMI in a machine with a Windows 8 Home Edition. I need to catch the CPU usage and the ProcessID by process. I've tried so many ways:
ShellExecute in Delphi
A *.bat with the code
A *.vbs
A *.vbs executed by a *.bat
A *.ps1
A *.ps1 executed by a *.bat
(Maybe some of these ways can be really stupid, but I've tried anyway)
In the User-Click it works perfectally, but by a standalone applicantion it doesn't work.
I have opened the Security on WMIMGMT.msi of some folders and the execution policy (in PowerShell) now is UNRESTRICTED.
This is the code on the *.ps1 file:
$ErrorActionPreference = "SilentlyContinue"
Stop-Transcript | Out-Null
$ErrorActionPreference = "Continue"
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
foreach ($p in $peflist) {
"" + $p.IDProcess + ";" + $p.PercentProcessTime
}
This is the code on *.bat
powershell -ExcetutionPolicy Unrestricted -File "C:\Somefolder\PP.ps1" > C:\SomeFolder\output.txt
All I got is this output:
get-wmiobject : Invalid query "select * from Win32_Win32_PerfFormattedData_PerfProc_Process"
In C:\Somefolder\PP.ps1:4 character: 14
+ $perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErroID : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Edit1: The code copied as asked:
*.ps1:
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
foreach ($p in $perflist) {
"" + $p.IDProcess + ";" + $p.PercentProcessorTime
}
*.bat
powershell -executionPolicy unrestricted -file "C:\MonitorPerformance\test.ps1" > C:\MonitorPerformance\output1.txt
Output: (Consulta inválida = Invalid Query; No = in; caractere = character)
get-wmiobject : Consulta inv lida "select * from Win32_PerfFormattedData_PerfProc_Process"
No C:\MonitorPerformance\test.ps1:4 caractere:14
+ $perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
replace this:
$perflist = (get-wmiobject Win32_Win32_PerfFormattedData_PerfProc_Process)
with this:
$perflist = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
Windows 8 does not performs WMI actions perfectly when you use x32 applications, I made a dummy x64 application who executes the *.bat and it finally works. Thanks for all the help.
I'm trying to run the code below via a script in a SQL agent job on a drive which is failing. When I logon as the service account user and run it in an ISE shell it works fine which leads me to believe it's not access related.
I tried running it as a PowerShell job step but it wouldn't work so decided to run it as a cmdexec job type and call it like this:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1"
Script
$ComputerName = "servername"
$KeyFolder = "\\servername\sharename\SSRSKEYS\"
$KeyPassword = "Password1"
$TimeStamp = Get-Date -Format "-yyyyMMdd-HHmmss"
Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer" -Class "__Namespace" -ComputerName $ComputerName |
Select-Object -ExpandProperty Name |
% {
$NameSpaceRS = $_
$InstanceName = $NameSpaceRS.SubString(3)
$KeyFileName = Join-Path -Path $KeyFolder -ChildPath ($InstanceName + $Timestamp + ".snk")
$SQLVersion = (Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)" -Class "__Namespace" - ComputerName $ComputerName).Name
$SSRSClass = Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)\$($SQLVersion)\Admin" - Query "SELECT * FROM MSReportServer_ConfigurationSetting WHERE InstanceName='$($InstanceName)'" -ComputerName $ComputerName
$Key = $SSRSClass.BackupEncryptionKey($KeyPassword)
If ($Key.HRESULT -ne 0) {
$Key.ExtendedErrors -join "`r`n" | Write-Error
} Else {
$Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length)
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length)
$Stream.Close()
}
}
Error
Executed as user: domain\svc_account. Exception calling "Create" with "2"
argument(s): "Access to the path '\\servername\sharename\SSRSKEYS\MSSQLSERVER-20150824-125254.snk' is denied." At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:24 char:13 + $Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +
CategoryInfo : NotSpecified: (:) [], MethodInvocationException +
FullyQualifiedErrorId : UnauthorizedAccessException You cannot call a
method on a null-valued expression. At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:25 char:13 +
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length) +
Try passing the script path to the PowerShell.exe as a parameter using the & operator, e.g.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "& 'F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1'"
The call operator (&) allows you to execute a command, script or function.
Syntax
& "[path] command" [arguments]
I am unable to run an invoke-command script to install printers on a remote machine. My code works locally, but as soon as I pipe it into Invoke-command, i get errors.
Local:
$Printer = "\\server1\printer1"
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($Printer)
And this adds the printer just fine. I can do this same command on the remote computer with no issues. But when i tried to execute the command remotely I have the issues.
Remote:
$compname = "computer"
$Printer = "\\server1\printer1"
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')}
Which returns the error "The printer name is invalid"
So I tried to see what the shell was sending to the remote computer with the following code, and everything in the write output looks good, but I still get errors:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer'); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')"}
Output:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : computer
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('\\server1\printer1')
Edit 1/5/2015
So I've tried Paul's code with a number of different entries to the argumentlist. All have not worked so far. i think the first 3 are closer to an answer.
-ArgumentList ""\\server1\printer1""
-ArgumentList ""'\\server1\printer1'""
-ArgumentList "\"\\server1\printer1""
Results in:
Invoke-Command : A positional parameter cannot be found that accepts argument '\\server1\printer1'.
At line:1 char:1
+ Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Ne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
-ArgumentList "'\\server1\printer1'"
-ArgumentList \'"\\server1\printer1"'
-ArgumentList \""\\server1\printer1""
-ArgumentList \"\\server1\printer1"
Result in:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : sso-mxl327082y
Try this:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($args[0]); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($($args[0]))"} -ArgumentList "\\server1\printer1"
I think it´s because your $printer variable is placed between single quotes, variables between single quotes are not interpreted by powershell. So the printername your function probably gets is "$printer".
In case you wonder it is printed out correctly in your write-host statement because here the single quotes are inside a string.
you need to use $Using:yourvar to pass variables to the scriptblock
$compname = "computer"
$Printer = "\\server1\printer1"
Invoke-Command -ComputerName $CompName -Scriptblock
{
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($Using:$Printer)
}
I think it's because of the so called 'double hop problem', where your authentication isn't transfered to the next remote computer which is sharing the printer.
I tried to solve similar problem using add-printer and following this article double hop problem solution.
However, although it works with get-childitem etc. it doesn't work with add-printer cmdlet.
I want to execute below code in the either local or remote machine whith current user.
$BackUpSqlAgentAndRemoveOldbackup = {
param([string]$AppServer,[string]$SqlInstance,[string]$BackupShare,[string]$alias)
[Environment]::UserName #I got same user name in all cases.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $SqlInstance
$backupName = 'SqlAgentJob_' + $SqlInstance + '_' + (Get-Date –format ‘yyyyMMdd_HHmm’) + '_' + $alias + '.sql'
$backupPath = join-path $BackupShare $backupName
$oldBackups = Get-ChildItem $backupShare | where { ( $_.name -like 'SqlAgentJob_*.sql' ) }
$server.JobServer.Jobs.Script() | Out-File -filepath $backupPath
foreach ( $item in $oldBackups ) { remove-item $item.fullName }
}
the #argList is
#('hafcapp-1', 'hafcsql-1', '\\Host5FileSrv\Backup\test','auto')
I notice that
this one, it works well (no -comupterName and -session)
Invoke-Command -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
this one, it throw execption (I also tried "-session", get same result)
Invoke-Command -computerName localhost -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
the exception is as below, it seems the it can not access the folder.
Cannot find path '\\Host5FileSrv\Backup\test' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\Host5FileSrv\Backup\test:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (Script:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
does anyone know how can I do if I want to add computerName or session?
(notes:[Environment]::UserName return identical user)
You have run into the double hop problem. Your credentials can be transferred to the next machine (first hop), but no further (second hop). This means that you can't use the credentials of the machine where you are executing Invoke-Command on, the remote machine (localhost) to connect to a file share (\Host5FileSrv\Backup). Even if you use localhost as computername, it is still remoting. A solution could be CredSSP. See here and here for more information.
This looks like a "second hop" remoting problem, and you'll need to configure WinRM on the computers involved to use CredSSP
http://msdn.microsoft.com/en-us/library/windows/desktop/ee309365(v=vs.85).aspx