WMI Scripting Windows 8 error - powershell

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.

Related

Powershell - This command cannot be run

I have a C++ application that launches a ps1 script using the following command
ShellExecuteA(0, "open", "powershell.exe", -executionpolicy RemoteSigned -File script.ps1", NULL, SW_NORMAL)
The script contains the following
$version = [System.Environment]::OSVersion.Version.Major
if ($version -gt 9)
{
$app = 'C:\Windows\System32\uwfmgr.exe'
$appargs = 'servicing enable'
Start-Process $app $appargs
Start-Sleep -s 5
$appargs= 'filter restart'
Start-Process $app $appargs
}
The end result should be that the Windows 10 machine (protected by UWF) should request service mode on its next reboot and the computer should restart
What happens instead is that the following error is raised
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At script.ps1:6 char: 2
+ Start-Process $app $args
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Edit:
Added
$Error[0] | FL * -Force
and renamed $args to $appargs

'Provider load failure' during installation process

I execute two Powershell scripts during a installation process from a desktop application under Windows 10 IoT Enterprise.
%WINDIR%\System32\WindowsPowerShell\v1.0\PowerShell.exe -ExecutionPolicy Bypass -File ".\KeyboardFilter.ps1"
%WINDIR%\System32\WindowsPowerShell\v1.0\PowerShell.exe -ExecutionPolicy Bypass -File ".\ShellLauncher.ps1"
But the execution of the Powershell scripts is not successful. I get the following errors:
Get-WMIObject : Provider load failure
At C:\Program Files\Application\KeyboardFilter.ps1:31 char:19
+ ... $predefined = Get-WMIObject -class WEKF_PredefinedKey #CommonParams |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Write-Error : A positional parameter cannot be found that accepts argument 'is'.
At C:\Program Files\Application\KeyboardFilter.ps1:41 char:9
+ Write-Error $Id is not a valid predefined key
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Write-Error], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteErrorCommand
enable-windowsoptionalfeature : An attempt was made to load a program with an incorrect format.
At C:\Program Files\Application\ShellLauncher.ps1:4 char:1
+ enable-windowsoptionalfeature -online -featureName Client-EmbeddedShe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Enable-WindowsOptionalFeature], COMException
+ FullyQualifiedErrorId : Microsoft.Dism.Commands.EnableWindowsOptionalFeatureCommand
The installation process starts with administration permissions.
The first script adds key combinations to the Keyboard Filter (Windows 10 IoT feature).
The second scripts enable and configure the Shell Launcher (also Windows 10 IoT feature).
KeyboardFilter.ps1:
param (
[String] $ComputerName
)
$CommonParams = #{"namespace"="root\standardcimv2\embedded"}
$CommonParams += $PSBoundParameters
function Enable-Predefined-Key($Id) {
$predefined = Get-WMIObject -class WEKF_PredefinedKey #CommonParams |
where {
$_.Id -eq "$Id"
};
if ($predefined) {
$predefined.Enabled = 1;
$predefined.Put() | Out-Null;
Write-Host Enabled $Id
} else {
Write-Error $Id is not a valid predefined key
}
}
If I execute the Powershell scripts in a batchfile or on Powershell console, everything works fine. I also tried to execute the Powershell scripts during the installation process with Powershell x86 and x64, same errors in both cases.
Any hints, tips or solution for this problem?

Powershell activate Windows 10 WMIMethodException

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

PowerShell script inside SQL Agent job error

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]

powershell invoke-command does not work if I use -computerName

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