How to use powershell.exe with -Command using a scriptblock and parameters - powershell

For reasons that should not impact the current question I need to run a script, with the definition and parameters outside the command, inside a different PowerShell instance, without using PSSessions, background jobs or files (I have working examples for PSSession, background jobs and .ps1 files and I'm aware they can replace what I'm trying to do, but I need a working example with powershell.exe -Command as well).
I looked at the help for powershell.exe, and it should support what I am trying to do, but I can't get it working with all that I need (script definition and parameters outside the command).
As a working example I have:
$abc = powershell.exe -WindowStyle Hidden -NonInteractive -Command {Invoke-Command -ScriptBlock {
param($a1,$a2)
$a1*6
$a2*5} -Argumentlist #(8,'abc')}
I need to be able to at least move the -ArgumentList outside the command, like:
$abc = powershell.exe -WindowStyle Hidden -NonInteractive -Command {Invoke-Command -ScriptBlock {
param($a1,$a2)
$a1*6
$a2*5} -Argumentlist #($args[0],$args[1])} -args #(8,'abc')
and even better have:
$script={
param($a1,$a2)
$a1*6
$a2*5}
$args=#(8,'abc')
$abc = powershell.exe -WindowStyle Hidden -NonInteractive -Command $script -args $args
I already looked at the following similar questions, but couldn't find what I needed:
How to run a Powershell script from the command line and pass a directory as a parameter
How can I Start-Process powershell.exe with some string splitter?

Not sure if this helps I added a few things to your original script and changed $args to $z and it seemed to work.
$script={
param($a1 =1 ,$a2 = 2)
$a1*6
$a2*5
test-connection -Count 2 www.google.com
Write-Output $a1
Write-Output $a2
}
$z=#(8,'abc')
$abc = powershell.exe -WindowStyle Hidden -NonInteractive -Command $script -args $z
$abc
48
abcabcabcabcabc
PSComputerName : ok
IPV4Address :1.1.1.4
IPV6Address :
__GENUS : 2
__CLASS : Win32_PingStatus
__SUPERCLASS :
__DYNASTY : Win32_PingStatus
__RELPATH : Win32_PingStatus.Address="www.google.com",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,SourceRou
te="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
__PROPERTY_COUNT : 24
__DERIVATION : {}
__SERVER : ok
__NAMESPACE : root\cimv2
__PATH : \\ok\root\cimv2:Win32_PingStatus.Address="www.google.com",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressName
s=FALSE,SourceRoute="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Address : www.google.com
BufferSize : 32
NoFragmentation : False
PrimaryAddressResolutionStatus : 0
ProtocolAddress :1.1.1.4
ProtocolAddressResolved :
RecordRoute : 0
ReplyInconsistency : False
ReplySize : 32
ResolveAddressNames : False
ResponseTime : 19
ResponseTimeToLive : 252
RouteRecord :
RouteRecordResolved :
SourceRoute :
SourceRouteType : 0
StatusCode : 0
Timeout : 4000
TimeStampRecord :
TimeStampRecordAddress :
TimeStampRecordAddressResolved :
TimestampRoute : 0
TimeToLive : 80
TypeofService : 0
PSComputerName : ok
IPV4Address :1.1.1.4
IPV6Address :
__GENUS : 2
__CLASS : Win32_PingStatus
__SUPERCLASS :
__DYNASTY : Win32_PingStatus
__RELPATH : Win32_PingStatus.Address="www.google.com",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,SourceRou
te="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
__PROPERTY_COUNT : 24
__DERIVATION : {}
__SERVER : ok
__NAMESPACE : root\cimv2
__PATH : \\ok\root\cimv2:Win32_PingStatus.Address="www.google.com",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressName
s=FALSE,SourceRoute="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Address : www.google.com
BufferSize : 32
NoFragmentation : False
PrimaryAddressResolutionStatus : 0
ProtocolAddress :1.1.1.4
ProtocolAddressResolved :
RecordRoute : 0
ReplyInconsistency : False
ReplySize : 32
ResolveAddressNames : False
ResponseTime : 21
ResponseTimeToLive : 252
RouteRecord :
RouteRecordResolved :
SourceRoute :
SourceRouteType : 0
StatusCode : 0
Timeout : 4000
TimeStampRecord :
TimeStampRecordAddress :
TimeStampRecordAddressResolved :
TimestampRoute : 0
TimeToLive : 80
TypeofService : 0
8
abc

This answer isn't 100% relevant to the original poster, because they are trying to run PowerShell from within PowerShell. I am trying to run it PowerShell from either a command prompt, or specifically WMI. A little background: the reason I'm trying to do this is because PowerShell remoting is not enabled on my target machine and I want to enable it. I can't use winrm because it requires user input. So, this works:
$x=Get-WmiObject -ComputerName "<computer name>" -Namespace "root\cimv2" -Class "Win32_Process" -List
$x.Create('C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command {Enable-PSRemoting}"',$null,$null)
Results:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ProcessId : 12508
ReturnValue : 0
PSComputerName :
I should probably post this in a different question, but this one came up on a google search for "how to pass scriptblock to powershell.exe", so I thought it would be useful here.

Related

Select Time property from Test-Connection in Powershell

Hello I found this script online below and I am trying to add time as a output but it seems like I cannot select time from test-connection command. I can select for address but not time?
#selecting for address works
Test-Connection -computername 10.15.31.1 | select Address
#selecting for time does not work
Test-Connection -computername 10.15.31.1 | select Time
#You can see below what I am trying to achieve
$output=foreach ($name in $names) {
[PSCustomObject][ordered]#{
Source= $ipaddress
Destination = $name
# Time=Test-Connection -computername 10.15.31.1 | select Time
Ping = Test-Connection -ComputerName $name -Quiet -Count 1
}
}
So lets figure this out.
(Test-Connection -computername 8.8.8.8 -Count 1) | select *
Will bring back
PSComputerName : Test-Computer
IPV4Address : 8.8.4.4
IPV6Address :
__GENUS : 2
__CLASS : Win32_PingStatus
__SUPERCLASS :
__DYNASTY : Win32_PingStatus
__RELPATH : Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,SourceRoute="",SourceRouteType
=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
__PROPERTY_COUNT : 24
__DERIVATION : {}
__SERVER : Test-Computer
__NAMESPACE : root\cimv2
__PATH : \\Test-Computer\root\cimv2:Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,Source
Route="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Address : 8.8.8.8
BufferSize : 32
NoFragmentation : False
PrimaryAddressResolutionStatus : 0
ProtocolAddress : 8.8.8.8
ProtocolAddressResolved :
RecordRoute : 0
ReplyInconsistency : False
ReplySize : 32
ResolveAddressNames : False
ResponseTime : 16
ResponseTimeToLive : 54
RouteRecord :
RouteRecordResolved :
SourceRoute :
SourceRouteType : 0
StatusCode : 0
Timeout : 4000
TimeStampRecord :
TimeStampRecordAddress :
TimeStampRecordAddressResolved :
TimestampRoute : 0
TimeToLive : 80
TypeofService : 0
Scope : System.Management.ManagementScope
Path : \\Test-Computer\root\cimv2:Win32_PingStatus.Address="8.8.8.8",BufferSize=32,NoFragmentation=false,RecordRoute=0,ResolveAddressNames=false,Source
Route="",SourceRouteType=0,Timeout=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0
Options : System.Management.ObjectGetOptions
ClassPath : \\Test-Computer\root\cimv2:Win32_PingStatus
Properties : {Address, BufferSize, NoFragmentation, PrimaryAddressResolutionStatus...}
SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers : {dynamic, provider}
Site :
Container :
We can see that you are looking for ResponseTime
Test-Connection -computername 8.8.8.8 | select ResponseTime
Will Return
ResponseTime
------------
18
18
15
13
Now Test-Connection -computername 8.8.8.8 -Quiet
Will only return a $true or $false so make sure you DO NOT use that if you are trying to get more detailed information.

Change RDP with Invoke-WmiMethod

I want change RDP port with WMI method but my code doesn't work and I don't know why.
Invoke-WmiMethod -Class StdRegprov -Name SetDWORDvalue -ArgumentList 2147483650,"System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp", "PortNumber", 3354
I get this after execute in PowerShell:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 5
PSComputerName :
But nothing changed?
This right here indicates your problem:
ReturnValue : 5
Return code 5 means "access denied". Your user does not have permission to write to that registry location. You probably need to run the code "as administrator".
With that said, PowerShell provides direct access to the registry. You don't need WMI for that.
$reg = 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp'
$name = 'PortNumber'
$value = 3354
New-ItemProperty -Path $reg -Name $name -Value $value -Type DWORD -Force | Out-Null
You still need to run this with a user who has write access to the registry key, though.

How to Subscribe to Windows File Modification Events

I am trying to subscribe to the event of a specific file being modified using WQL with this query:
SELECT * FROM __InstanceModificationEvent WITHIN 1 WHERE TargetInstance ISA "CIM_DataFile" AND TargetInstance.Drive="C:" AND TargetInstace.Path="\\test\\filewatching\\"
I can register the event successfully (see output at the bottom) and can see it is bound with the script that I registered with (the consumer).
However, when I modify a file in C:\test\filewatching\ the script does not run.
Here is the code for registering for a File Creation Event in the same folder, and this works:
#WQL
$query = #"
SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA "Cim_DirectoryContainsFile" AND TargetInstance.GroupComponent="Win32_Directory.Name='C:\\test\\filewatching'"
"#
$instanceFilter = ([WMICLASS]"\\$Computername\root\subscription:__EventFilter").CreateInstance()
$instanceFilter.QueryLanguage = 'WQL'
$instanceFilter.Query = $query
$instanceFilter.Name = 'EventFilterNameHere'
$instanceFilter.EventNameSpace = 'root/CIMV2'
$result = $instanceFilter.Put()
# Consumer
$script =
#"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\test\filewatching\Log.log", 8, True)
objFile.WriteLine "New File Created"
objFile.Close
"#
$instanceConsumer = ([wmiclass]"\\$Computername\root\subscription:ActiveScriptEventConsumer").CreateInstance()
$instanceConsumer.Name = 'ConsumerNameHere'
$instanceConsumer.ScriptingEngine = 'VBScript'
$instanceConsumer.ScriptFilename = ''
$instanceConsumer.ScriptText = $script
$instanceConsumer.Put()
# Binding
[object]$Filter = (Get-WMIObject -Computername $Computername -Namespace root\Subscription -Class __EventFilter | Sort Name)
[object]$Consumer = (Get-WMIObject -Computername $Computername -Namespace root\Subscription -Class __EventConsumer | Sort Name)
$instanceBinding = ([wmiclass]"\\$Computername\root\subscription:__FilterToConsumerBinding").CreateInstance()
$instanceBinding.Filter = $Filter
$instanceBinding.Consumer = $Consumer
$instanceBinding.Put()
So I know there is nothing wrong with my PowerShell. This makes me think that my query must be wrong.
I have tried a few tweaks of the above InstanceModificationEvent query, but with no success. (these tweaks include stuff like changing C: to C or removing \s from the TargetInstace.Path).
I need this subscription to be permanent and it can't reset if the PC is turned on or off - this is why I am using WQL. If anyone can suggest another way of achieving the same or how I can fix my query I will be eternally grateful!
Output after running the script:
Path : \\WIN7-IT3\root\subscription:ActiveScriptEventConsumer.Name="Co
nsumerNameHere"
RelativePath : ActiveScriptEventConsumer.Name="ConsumerNameHere"
Server : WIN7-IT3
NamespacePath : root\subscription
ClassName : ActiveScriptEventConsumer
IsClass : False
IsInstance : True
IsSingleton : False
Path : \\WIN7-IT3\root\subscription:__FilterToConsumerBinding.Consumer
="\\\\WIN7-IT3\\ROOT\\Subscription:ActiveScriptEventConsumer.Na
me=\"ConsumerNameHere\"",Filter="\\\\WIN7-IT3\\ROOT\\Subscripti
on:__EventFilter.Name=\"EventFilterNameHere\""
RelativePath : __FilterToConsumerBinding.Consumer="\\\\WIN7-IT3\\ROOT\\Subscri
ption:ActiveScriptEventConsumer.Name=\"ConsumerNameHere\"",Filt
er="\\\\WIN7-IT3\\ROOT\\Subscription:__EventFilter.Name=\"Event
FilterNameHere\""
Server : WIN7-IT3
NamespacePath : root\subscription
ClassName : __FilterToConsumerBinding
IsClass : False
IsInstance : True
IsSingleton : False
Querying WMI subscriptions:
Get-WmiObject -Namespace root\Subscription -Class __Eventfilter
Get-WMIObject -Namespace root\Subscription -Class __EventConsumer
Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding
Get-WMIObject -Namespace root\Subscription -Class ActiveScriptEventConsumer
Output after querying:
__GENUS : 2
__CLASS : __EventFilter
__SUPERCLASS : __IndicationRelated
__DYNASTY : __SystemClass
__RELPATH : __EventFilter.Name="EventFilterNameHere"
__PROPERTY_COUNT : 6
__DERIVATION : {__IndicationRelated, __SystemClass}
__SERVER : WIN7-IT3
__NAMESPACE : ROOT\Subscription
__PATH : \\WIN7-IT3\ROOT\Subscription:__EventFilter.Name="EventFilterNameHere"
CreatorSID : {1, 5, 0, 0...}
EventAccess :
EventNamespace : root/CIMV2
Name : EventFilterNameHere
Query : SELECT * FROM __InstanceModificationEvent WITHIN 5 WHERE TargetInstance ISA
"CIM_DataFile" AND TargetInstance.Drive="C:" AND
TargetInstace.Path="\\test\\filewatching\\"
QueryLanguage : WQL
PSComputerName : WIN7-IT3
__GENUS : 2
__CLASS : ActiveScriptEventConsumer
__SUPERCLASS : __EventConsumer
__DYNASTY : __SystemClass
__RELPATH : ActiveScriptEventConsumer.Name="ConsumerNameHere"
__PROPERTY_COUNT : 8
__DERIVATION : {__EventConsumer, __IndicationRelated, __SystemClass}
__SERVER : WIN7-IT3
__NAMESPACE : ROOT\Subscription
__PATH : \\WIN7-IT3\ROOT\Subscription:ActiveScriptEventConsumer.Name="ConsumerNameHere"
CreatorSID : {1, 5, 0, 0...}
KillTimeout : 0
MachineName :
MaximumQueueSize :
Name : ConsumerNameHere
ScriptFilename :
ScriptingEngine : VBScript
ScriptText : Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\test\filewatching\Log.log", 8, True)
objFile.WriteLine "New File Created"
objFile.Close
PSComputerName : WIN7-IT3
__GENUS : 2
__CLASS : __FilterToConsumerBinding
__SUPERCLASS : __IndicationRelated
__DYNASTY : __SystemClass
__RELPATH : __FilterToConsumerBinding.Consumer="\\\\WIN7-IT3\\ROOT\\Subscription:ActiveS
criptEventConsumer.Name=\"ConsumerNameHere\"",Filter="\\\\WIN7-IT3\\ROOT\\Su
bscription:__EventFilter.Name=\"EventFilterNameHere\""
__PROPERTY_COUNT : 7
__DERIVATION : {__IndicationRelated, __SystemClass}
__SERVER : WIN7-IT3
__NAMESPACE : ROOT\Subscription
__PATH : \\WIN7-IT3\ROOT\Subscription:__FilterToConsumerBinding.Consumer="\\\\WIN7-IT
3\\ROOT\\Subscription:ActiveScriptEventConsumer.Name=\"ConsumerNameHere\"",F
ilter="\\\\WIN7-IT3\\ROOT\\Subscription:__EventFilter.Name=\"EventFilterName
Here\""
Consumer : \\WIN7-IT3\ROOT\Subscription:ActiveScriptEventConsumer.Name="ConsumerNameHer
e"
CreatorSID : {1, 5, 0, 0...}
DeliverSynchronously : False
DeliveryQoS :
Filter : \\WIN7-IT3\ROOT\Subscription:__EventFilter.Name="EventFilterNameHere"
MaintainSecurityContext : False
SlowDownProviders : False
PSComputerName : WIN7-IT3
__GENUS : 2
__CLASS : ActiveScriptEventConsumer
__SUPERCLASS : __EventConsumer
__DYNASTY : __SystemClass
__RELPATH : ActiveScriptEventConsumer.Name="ConsumerNameHere"
__PROPERTY_COUNT : 8
__DERIVATION : {__EventConsumer, __IndicationRelated, __SystemClass}
__SERVER : WIN7-IT3
__NAMESPACE : ROOT\Subscription
__PATH : \\WIN7-IT3\ROOT\Subscription:ActiveScriptEventConsumer.Name="ConsumerNameHere"
CreatorSID : {1, 5, 0, 0...}
KillTimeout : 0
MachineName :
MaximumQueueSize :
Name : ConsumerNameHere
ScriptFilename :
ScriptingEngine : VBScript
ScriptText : Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\test\filewatching\Log.log", 8, True)
objFile.WriteLine "New File Created"
objFile.Close
PSComputerName : WIN7-IT3
Stumbled across this page soon after posting this question, from which I worked out that the query I need is:
SELECT * FROM __InstanceModificationEvent WITHIN 1 WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Name='c:\\test\\filewatching\\tester.txt'
Notice that contrary to several other posts online, what worked for me was actually to omit the Path and Drive parts of TargetInstance and only included the full path and name for the file I want to watch.
This works for me because I will only be watching 1 specific file. If you need to watch multiple files using this method you will need to register multiple subscriptions.
The full code for registering a File Modification watcher:
#WQL
$query = #"
SELECT * FROM __InstanceModificationEvent WITHIN 1 WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Name='c:\\test\\filewatching\\tester.txt'
"#
$instanceFilter = ([WMICLASS]"\\$Computername\root\subscription:__EventFilter").CreateInstance()
$instanceFilter.QueryLanguage = 'WQL'
$instanceFilter.Query = $query
$instanceFilter.Name = 'EventFilterNameHere'
$instanceFilter.EventNameSpace = 'root/CIMV2'
$result = $instanceFilter.Put()
# Consumer
$script =
#"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\test\filewatching\Log.log", 8, True)
objFile.WriteLine "New File Created"
objFile.Close
"#
$instanceConsumer = ([wmiclass]"\\$Computername\root\subscription:ActiveScriptEventConsumer").CreateInstance()
$instanceConsumer.Name = 'ConsumerNameHere'
$instanceConsumer.ScriptingEngine = 'VBScript'
$instanceConsumer.ScriptFilename = ''
$instanceConsumer.ScriptText = $script
$instanceConsumer.Put()
# Binding
[object]$Filter = (Get-WMIObject -Computername $Computername -Namespace root\Subscription -Class __EventFilter | Sort Name)
[object]$Consumer = (Get-WMIObject -Computername $Computername -Namespace root\Subscription -Class __EventConsumer | Sort Name)
$instanceBinding = ([wmiclass]"\\$Computername\root\subscription:__FilterToConsumerBinding").CreateInstance()
$instanceBinding.Filter = $Filter
$instanceBinding.Consumer = $Consumer
$instanceBinding.Put()
you need to attach the path of the consumer and filter to the binder
instead of every filter\consumer in the system
$result = $instanceFilter.Put()
$filterPath = $result.Path
$result = $instanceConsumer.Put()
$consumerPath = $result.Path
$bind.Filter = $filterPath
$bind.Consumer = $consumerPath

CommandNotFoundException: get-windowsoptionalfeature

I am using Powershell Version 2 on windows 7. I need to run the following command: get-windowsoptionalfeature
but when I run: get-command -Verb Get, the get-windowsoptionalfeature is not listed and as a result when I enter the command I receive an error stating that "get-windowsoptionalfeature" is not recognized as the name of a cmdlet, function.
Am I missing a dll or something?
get-windowsoptionalfeature is only applicable to Windows 8 & Server 2012.
try this in powershell console
PS C:\>$feature=Get-WmiObject -query "select * from Win32_OptionalFeature"
Now $feature is array of object of type ManagementObject.
to prove it try
PS C:\> $feature[0]
this is what I get.
__GENUS : 2
__CLASS : Win32_OptionalFeature
__SUPERCLASS : CIM_LogicalElement
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_OptionalFeature.Name="OEMHelpCustomization"
__PROPERTY_COUNT : 6
__DERIVATION : {CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : TTL001343
__NAMESPACE : root\cimv2
__PATH : \\TTL001343\root\cimv2:Win32_OptionalFeature.Name="OEMHelpCustomization"
Caption :
Description :
InstallDate :
InstallState : 2
Name : OEMHelpCustomization
Status :
You can get query specific objects as well.
example:
PS C:\>$feature=Get-WmiObject -query "select * from Win32_OptionalFeature where name = 'RemoteServerAdministrationTools-Roles-AD-Powershell'"
Now this will be single object not an array.
There's the Client Manager Module:
http://archive.msdn.microsoft.com/PSClientManager

How can I use Invoke-WmiMethod to rename a computer

I am trying to call the Rename method on the Win32_ComputerSytem class using Invoke-WMI method. Using this syntax works fine
(gwmi win32_ComputerSystem).Rename("NEWNAME")
This also works fine for demo purposes
Invoke-WmiMethod -path win32_process -Name create -ArgumentList notepad
However, when i try the following, I get an error
11 > Invoke-WmiMethod -path win32_computersystem -Name Rename -ArgumentList IwasRenamed
Invoke-WmiMethod : Invalid method Parameter(s)
At line:1 char:17
+ Invoke-WmiMethod <<<< -path win32_computersystem -Name Rename -ArgumentList IwasRenamed
+ CategoryInfo : InvalidOperation: (:) [Invoke-WmiMethod], ManagementExcepti
on
+ FullyQualifiedErrorId : InvokeWMIManagementException,Microsoft.PowerShell.Commands.
InvokeWmiMethod
What am I missing?
You need to specify an instance of the class Win32_ComputerSystem using the Path parameter:
PS C:\Users\ben> $path = "Win32_ComputerSystem.Name='OLDNAME'"
PS C:\Users\ben> Invoke-WmiMethod -Name Rename -Path $path -ArgumentList "NEWNAME"
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
Which is functionally equivalent to the gwmi Rename syntax that you referred to. This syntax implicitly retrieves an instance of the class Win32_ComputerSystem to call the method on:
PS C:\Users\ben> (gwmi win32_computersystem).rename("NEWNAME")
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
Here's another cool syntax:
PS C:\Users\ben> ([wmi]"Win32_ComputerSystem.Name='OLDNAME'").Rename("NEWNAME")
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
The Rename method takes three parameters. I'm guessing Invoke-WmiMethod uses reflection to call the method, so you have to specify all three parameters. Try this:
[String]$newName = "IWasRenamed"
[String]$password = $null
[String]$username = $null
Invoke-WmiMethod -Path Win32_ComputerSystem -Name Rename -ArgumentList $newName, $password, $username