GithubHelp home page GithubHelp logo

mkellerman / invoke-commandas Goto Github PK

View Code? Open in Web Editor NEW
437.0 22.0 70.0 107 KB

Invoke Command As System/Interactive/GMSA/User on Local/Remote machine & returns PSObjects.

Home Page: https://www.powershellgallery.com/packages/Invoke-CommandAs/

License: MIT License

PowerShell 100.00%

invoke-commandas's People

Contributors

hartleyj avatar jcrumpton avatar kkawabanga avatar mkellerman avatar mlsmaycon avatar pshamus avatar spacecheetah avatar the-mentor avatar vandreytrindade avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

invoke-commandas's Issues

Not working when using variables in script block

EDIT: Looks like having parentheses around my command caused it to fail. Took the parenths out, and everything worked.

Trying this:

$var1 = "C:\Users<user><file>"
Invoke-CommandAs -Computername Comp1 -scriptblock {param($var1)(Get-Item -Force $var1)} -ArgumentList $var1 -AsSystem

Nothing returns...

If I do the normal Invoke-Command:
Invoke-Command -Computername DEN-DATA-RES01 -scriptblock {param($var1)(Get-Item -Force $var1)} -ArgumentList $var1 -AsSystem

it returns the output

Invoke-CommandAs -AsSystem broke on 2012 R2 ENG

Hello,

I have a issue on 2012 R2 ENG :

PS C:\Users\Administrator> Invoke-CommandAs -ScriptBlock { Get-Process } -AsSystem
New-ScheduledTaskAction : Invalid class
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.6\private\Invoke-ScheduledTask.ps1:89 char:49

  • ... 'Action'] = New-ScheduledTaskAction -Execute $ScheduledJob.PSExecutio ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : MetadataError: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [New-ScheduledTaskAc
      tion], CimException
    • FullyQualifiedErrorId : HRESULT 0x80041010,New-ScheduledTaskAction

New-ScheduledTaskPrincipal : Invalid class
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.6\private\Invoke-ScheduledTask.ps1:91 char:56

  • ... incipal'] = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : MetadataError: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [New-ScheduledTaskPr
      incipal], CimException
    • FullyQualifiedErrorId : HRESULT 0x80041010,New-ScheduledTaskPrincipal

Invoke-ScheduledTask : Cannot validate argument on parameter 'Principal'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.6\public\Invoke-CommandAs.ps1:399 char:17

  •             Invoke-ScheduledTask @Parameters
    
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-ScheduledTask

The version of powershell is 5.1

Thank for your help.

Calling via NT Authority\SYSTEM - requires elevation?

Invoke-ScheduledTask : An access denied error occurred when registering scheduled job definition
ffbf27f4-e979-425a-a56e-71d3837cabfc. Try running Windows PowerShell with elevated user rights; that is, Run As
Administrator.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.9\public\Invoke-CommandAs.ps1:399 char:17

  •             Invoke-ScheduledTask @Parameters
    
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-ScheduledTask

Context- The above error is generated when calling the command via SYSTEM, specifically using an EC2 instance userdata script..

Windows server 2022 host, and the $Credentials are part of the local administrators group
here is an example of the command I used:

if (-not (Test-Path "C:\Program Files\Program")) { Invoke-CommandAs -ScriptBlock { Start-Process "c:\binaries\setup.exe" '/HIDDEN /NOUSERINPUT /SCRIPT C:\binaries\Install.ini' } -AsUser $Credentials }

Any ideas?

Runs fine when called manually via an administrative powershell session... I did not think SYSTEM would require elevation?

Issue with Invoke-ScheduleTask not having output

Seems like there is an issue with the Invoke-ScheduledTask is not produce an output. I think this is due to a race condition between the Task being executed, and the ScheduledJob receiving/capturing the output. Instead of waiting for the ScheduledJob to complete, I'll make it wait for the task to be completed.

Would it be possible to run -AsLocalService

I'd like to invoke as NT AUTHORITY\LOCAL SERVICE instead of System which has a bit too much power for what I need.

I tried to implement it myself but it doesn't seem to work -- likely because the local service cannot create scheduled tasks or something like that? I'm a bit out of my comfort zone here :-) Is there a workaround?

PS Remoting is disabled.

I am unable to use invoke-comandas because powershell remoting is prohibited from being enabled.

I have been executing powershell scriptblocks remotely using wmi and would love to see if this functionality be added if possible.

here is what I have been using:

function Invoke-ScheduledScriptBlock {
[CmdletBinding()]
param
(
[Parameter()]
[string[]]$ComputerName ,

    [ValidateNotNull()]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential = [System.Management.Automation.PSCredential]::Empty  ,
    [ScriptBlock]$ScriptBlock
)

$username = $Credential.Username
$password = $Credential.GetNetworkCredential().Password
$command = $scriptblock.ToString()
$command = $command + ' ; start-sleep -Seconds 2 ; SCHTASKS /Delete /TN OnDemand /F'
if($command.Length -lt '200'){
$script = @"
`$powerShellCommand =
"powershell.exe -noprofile -executionpolicy Unrestricted -command $command "

schtasks /CREATE /TN 'OnDemand' /SC WEEKLY /RL HIGHEST /RU $username /RP $password
/TR "`$powerShellCommand" /F

schtasks /RUN /TN 'OnDemand' | Out-String
"@
} Else {
$ps1 = ([system.guid]::newguid().tostring().split('-')[0]) + '.ps1'
$command | Out-File "\$ComputerName\c$\Windows\Temp$ps1" -Force

$script = @"
`$powerShellCommand =
"powershell.exe -noprofile -executionpolicy Unrestricted -file c:\windows\temp$ps1 "

schtasks /CREATE /TN 'OnDemand' /SC WEEKLY /RL HIGHEST /RU $username /RP $password
/TR "`$powerShellCommand" /F

schtasks /RUN /TN 'OnDemand' | Out-String
"@

}

$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($script)
$encoded = [Convert]::ToBase64String($commandBytes)
$command = "powershell -NoProfile -EncodedCommand $encoded"
$null = Invoke-WmiMethod -Computer $computername -Credential $AdminCred `
Win32_Process Create -Args $command

}

Erro running RunElevated parameter

Hi!
I was testing your module and the parameter RunElevated doesn't work as expected (at least I think).
What I've tried:

$PSsession = Enter-PSSession "COMPUTER"
$ScriptBlock = { [System.Security.Principal.Windowsidentity]::GetCurrent() }
Invoke-CommandAs -Session $PSSession -ScriptBlock { Get-Process } -AsSystem -RunElevated

It throws this error:

O conjunto de parâmetros não pode ser resolvido usando os parâmetros nomeados especificados.
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-ScheduledTask
    + PSComputerName        : EST001926

PowerShell version: 5.1.18362.145 (Windows 10 Pro latest version)

Windows 7 - Run with Highest Privileges

PSVersion - 5.1.14409.1018
OSVersion - 6.1.7601.65536
ModuleVersion - 3.1.2

I am seeing an issue where none of the scheduled tasks are set to run with highest privileges on Windows 7 (Have not spun up a 2k8r2 server yet to test). If I need to execute something only on the local machine, running as SYSTEM alleviates this. When I need to run as a specific user for network share access I can not execute as administrator, as this option is not set.

Unable to submit credential objects as arguments

Cannot serialize the credential. If this command is starting a workflow, the credentials cannot be persisted, because the process in which the workflow is started does not have permission to seri
alize credentials.
-- If the workflow was started in a PSSession to the local computer, add the EnableNetworkAccess parameter to the command that created the session.
-- If the workflow was started in a PSSession to a remote computer, add the Authentication parameter with a value of CredSSP to the command that created the session. Or, connect to a session conf
iguration that has a RunAsUser property value.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-ScheduledTask
+ PSComputerName :

Unable to invoke command as gMSA - v3.1.2

I'm currently running into an issue where I'm not able to run a command as a gMSA using v3.1.2 of this module. v3.1.1 works as expected.

I'm seeing this on Windows Server 2019 with Windows PowerShell 5.1.

Here is v3.1.1 working:

image

And here is v3.1.2 on the same server:

image

Here's the full console output:

PS C:\WINDOWS\system32> Import-Module Invoke-CommandAs -RequiredVersion 3.1.2
PS C:\WINDOWS\system32> Invoke-CommandAs -ScriptBlock { Get-Process | Select -First 10 } -AsGMSA 'domain\ManagedServiceAccount$'
A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:347 char:21
+ ...             $Using:_Function | ForEach-Object { Invoke-Expression $_  ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:348 char:21
+ ...             $Using:_Using | ForEach-Object { Set-Variable -Name $_.Na ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:351 char:25
+                     If ($Using:ScriptBlock)   { $Parameters['ScriptBl ...
+                         ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:352 char:25
+                     If ($Using:ArgumentList)  { $Parameters['Argument ...
+                         ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:353 char:25
+                     If ($Using:AsUser)        { $Parameters['AsUser'] ...
+                         ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:354 char:25
+                     If ($Using:AsSystem)      { $Parameters['AsSystem ...
+                         ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:355 char:25
+                     If ($Using:AsInteractive) { $Parameters['AsIntera ...
+                         ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:356 char:25
+                     If ($Using:AsGMSA)        { $Parameters['AsGMSA'] ...
+                         ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or
InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the
script block is invoked on a remote computer.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.2\public\Invoke-CommandAs.ps1:357 char:25
+                     If ($Using:IsVerbose)     { $Parameters['Verbose' ...
+                         ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : UsingWithoutInvokeCommand


cmdlet Invoke-ScheduledTask at command pipeline position 1
Supply values for the following parameters:
ScriptBlock:

(It ends up prompting me to supply a scriptblock to Invoke-ScheduledTask)

Please let me know if I can provide any other info, error dumps, or whatever else.

Error: InvalidOperation RuntimeException UsingWithoutInvokeCommand

Using file \Scripts\Invoke-CommandAs.ps1 downloaded from github. Testing on Windows 10 IoT Enterprise LTSC 2019 (ver 1809)

test.ps1 has 2 lines:

. $PSScriptRoot\Invoke-CommandAs.ps1
Invoke-CommandAs -ScriptBlock { Get-Process } -AsSystem

When running I get several error messages, the first one is:

A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script
workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer.
At C:\util\Invoke-CommandAs.ps1:555 char:21

  • ... $Using:Function | ForEach-Object { Invoke-Expression $ ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : UsingWithoutInvokeCommand

Add tagging to Azure pipeline for releases

Hi guys,
I really apriciete the possibility to download this module directly from GitHub. But since there are no tags here, I have to search appropriet commit hashes to ensure I always download correct version of this module in my CI pipelines.

Would you consider taging the releases? Thank you in advance for any response.

You cannot call a method on a null-valued expression.

I am getting the following error while running the command

You cannot call a method on a null-valued expression.
At S:\Philips\Apps\iSite\Tools\SHDBAutoDeployService\Sensors\Content\Invoke-CommandAs.psm1:194 char:59

  •             $UsingVariables = $ScriptBlock.ast.FindAll <<<< ({$args[0] -is [System.Management.Automation.Language
    

.UsingExpressionAst]},$True)
+ CategoryInfo : InvalidOperation: (FindAll:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

image

Running as a GMSA requires the GMSA to have Admin on the Server

When running as a GMSA, either locally or remotely, the GMSA must have admin on the server. If the GMSA doesn't have admin, the command will get stuck in a loop, waiting for Get-Job to return the job. I can see the Scheduled Task was started on the machine, but PowerShell returns a non 0 return code. Task Scheduler successfully completed task "\0ea45f2b-f78e-43fb-bc2e-83ae8448f2e4" , instance "{f056b0d6-764b-4128-8c0d-34071966797b}" , action "powershell.exe" with return code 2147942401.

Nothing happens

Nothing happens when I run the command, see below the $error
Powershell version is 5.1

Get-Job : The command cannot find the job because the job name bc725259-2000-4917-8639-276a36418032 was not found.
Verify the value of the Name parameter, and then try the command again.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\2.0\Invoke-CommandAs.psm1:208 char:36

  • ... -Not($Job = Get-Job -Name $ScheduledJob.Name -ErrorAction SilentlyCon ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (bc725259-2000-4917-8639-276a36418032:String) [Get-Job], PSArgumentExcep
      tion
    • FullyQualifiedErrorId : JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand

AsSystem doesn't seem to execute while device is on battery power

Hi
I'm trying to execute some scripts, order to display some popups in the users session - and I have succeeded in this, by using the -AsSystem and combining with RunAsUser.

But... it only works, when the laptop is not on batterypower.

I can run an whoami on batterypower as my self, but as soon as the AsUser flag is added it fails on battery only.

Best regards
Flemming

Module on Powershell Core

Hello

I've installed this module on Powershell Core for Linux. Powershell has imported successfully the module, but when I put the command in a powershell session I receive an error message, thath the term Invoke-CommandAs has not been recognized.

Is this module designed only for Powershell Desk on Windows?

Best Regards
Gennaro Piano

AsUser Doesn't Impersonate user

Running as system administrator, impersonating a user doesn't work. I expect whoami to return 'MyUser'.

PS C:\windows\system32> whoami
nt authority\system
PS C:\windows\system32> $user="MyUser"
PS C:\windows\system32> $pass="MyPass"
PS C:\windows\system32> $secpass = ConvertTo-SecureString $pass -AsPlainText -Force
PS C:\windows\system32> $cred = New-Object System.Management.Automation.PSCredential $user,$secpass
PS C:\windows\system32> Invoke-CommandAs -ScriptBlock { whoami } -AsUser $cred
nt authority\system

What is the license of this repo

I would like to include Invoke-CommandAs.psm1 locally rather than pulling it from a repository, however I'm not sure if I'm allowed to redistribute this script. Could you please specify what is the license of this repository?

Access is denied. on localhost

Getting access denied when running using invoke-commandas on the localhost see info below. the credential that I'm using has local admin rights.

PSVersion 5.1.14409.1018
Invoke-CommandAS 3.1.2

$cred = Get-Credential
$ScriptBlock = {dir}

Invoke-CommandAs -ScriptBlock $ScriptBlock -ComputerName localhost -Credential $cred -AsUser $cred

[localhost] Connecting to remote server localhost failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken

Issue with Windows 7 machines

When I run the command below against Windows 7 machines I am getting this error. I believe this used to happen in an earlier version.

C:\Scripts\PowerShell> invoke-commandas -ComputerName hslllp2 -ScriptBlock {choco list -lo} -AsSystem
The term 'Get-ScheduledTask' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-ScheduledTask
+ PSComputerName : hslllp2

One liner in README still seems to have trouble

Hi,

Thanks for closing #19. Not sure what the etiquette with this is, please let me know if it would have been better to make a comment on the old issue rather than opening this new one.

However, I'm still having trouble getting the one liner ((New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/mkellerman/Invoke-CommandAs/master/Scripts/Invoke-CommandAs.ps1") | iex) to work well, as the screenshot below shows:

image

Many thanks for your help with this, much appreciated !

he term 'Register-ScheduledJob' is not recognized as the name of a cmdlet....

add 'Import-Module PSScheduledJob' inside the scriptblock of invoke-command cos it throws an exception:

The term 'Register-ScheduledJob' is not recognized as the name of a cmdlet, function, script file, or 
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Access Denied with -RunElevated

Trying to run the below code in a non elevated powershell and get the following error message

$scriptblock = {get-process}
Invoke-CommandAs -ScriptBlock $scriptblock -RunElevated
Invoke-ScheduledTask : An access denied error occurred when registering scheduled job definition e44e0537-40c1-4a28-81ae-e56b4275aa69.  Try running Windows PowerShell with elevated user right
s; that is, Run As Administrator.
At C:\Program Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.5\public\Invoke-CommandAs.ps1:399 char:17
+                 Invoke-ScheduledTask @Parameters
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-ScheduledTask
$PSVersionTable

Name                           Value                                                                                                                                                           
----                           -----                                                                                                                                                           
PSVersion                      5.1.17763.503                                                                                                                                                   
PSEdition                      Desktop                                                                                                                                                         
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                         
BuildVersion                   10.0.17763.503                                                                                                                                                  
CLRVersion                     4.0.30319.42000                                                                                                                                                 
WSManStackVersion              3.0                                                                                                                                                             
PSRemotingProtocolVersion      2.3                                                                                                                                                             
SerializationVersion           1.1.0.1  
Get-Module

ModuleType Version    Name                                ExportedCommands                                                                                                                     
---------- -------    ----                                ----------------                                                                                                                     
Script     3.1.5      Invoke-CommandAs                    Invoke-CommandAs                                                                                                                     
Script     1.0.0.0    ISE                                 {Get-IseSnippet, Import-IseSnippet, New-IseSnippet}                                                                                  
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}                                                                   
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl, Get-AuthenticodeSignature...}                                            
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}                                                                            
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Connect-WSMan, Disable-WSManCredSSP, Disconnect-WSMan, Enable-WSManCredSSP...}                                                      
Binary     1.1.0.0    PSScheduledJob                      {Add-JobTrigger, Disable-JobTrigger, Disable-ScheduledJob, Enable-JobTrigger...}                                                     
Manifest   1.0.0.0    ScheduledTasks                      {Disable-ScheduledTask, Enable-ScheduledTask, Export-ScheduledTask, Get-ClusteredScheduledTask...}                                   

Removing entries from the Task Scheduler log

I use the -AsSystem often and I see that creates a new task each time so on my clients the Task Scheduler log is filling up with old entries. For now I will think of a way to clear these out myself but maybe there is something that can be done to remove these automatically? Just spit balling here.

PowerShell Core Compatiblility

With the introduction of PowerShell Core, we should consider making this module compatible with Linux/Mac.

This is a open discussion, of what would be needed, and what feature we would want to implement for non-windows OSes.

Let me know what you think, and if anyone is willing to work on this.

Add '-UseSSL' Parameter

In our Production environment, we have set winrm quickconfig -transport:https, in order to only enable the HTTPS WSMan listener (cert-based transport).

As such, when running, Invoke-Command, we must specify the -UseSSL parameter.

It would be awesome if we could also use a similar -UseSSL parameter in Invoke-CommandAs, as well.

Currently, we can do the following:

$Sess = New-PSSession -ComputerName FQDN.ubc.ca  -UseSSL
Invoke-CommandAs -Session $Sess -ScriptBlock { Get-Process } -AsSystem

This would just mean one less step on instantiating the PSSession.

Merci beaucoup!

Support for PowerShell 7

In PowerShell Core 6.2, this error is returned:
Invoke-ScheduledTask : The term 'Register-ScheduledJob' is not recognized as the name of a cmdlet, function, script file, or operable program.

Since the module leverages PSScheduledJobs which is not available in Core, this is expected.

However, in PowerShell 7 it seems like the PSScheduledJobs module is back, but there is a different error:

Invoke-CommandAs -ScriptBlock {whoami} -System Write-Error: C:\Users\janring\Documents\PowerShell\Modules\Invoke-CommandAs\3.1.6\public\Invoke-CommandAs.ps1 Line | 399 | Invoke-ScheduledTask @Parameters | ^ Cannot bind parameter 'ScriptBlock'. Cannot convert the " Param($Parameters) | $JobParameters = @{} If ($Parameters.ScriptBlock) { $JobParameters['ScriptBlock'] = | [ScriptBlock]::Create($Parameters.ScriptBlock) } If ($Parameters.ArgumentList) { | $JobParameters['ArgumentList'] = $Parameters.ArgumentList } If ($Parameters.Using) { | $Parameters.Using | % { Set-Variable -Name $_.Name -Value | ([System.Management.Automation.PSSerializer]::Deserialize($_.Value)) } Start-Job | @JobParameters | Receive-Job -Wait -AutoRemoveJob } Else { Invoke-Command | @JobParameters }" value of type "System.String" to type | "System.Management.Automation.ScriptBlock".

$PSVersionTable
PSVersion 7.0.0-rc.1
PSEdition Core
GitCommitId 7.0.0-rc.1
OS Microsoft Windows 10.0.18363
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

One liner in README doesn't work

Hi,

Appreciate your work with this, it's a very good script.

A very minor issue propped up recently due to what I believe is the splitting of the script into Public and Private directories. I've attached an image showing the problem.

This one liner, which I got from the helpful documentation, (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/mkellerman/Invoke-CommandAs/master/Invoke-CommandAs.psm1") | iex used to work very well a few days ago but is no longer working as of today. I tend to use it as it's very portable and doesn't require me to download the whole repo etc.

I've resorted to using the following workaround relying on the old, deleted file version but this isn't ideal as I'd like to be on the latest version of the script: (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/mkellerman/Invoke-CommandAs/f40ecf69a33d0cffae88d3370d5ee2a8240afd47/Invoke-CommandAs.psm1") | iex

It would be great if we can please have a working one liner solution for this if possible, many thanks for all your hard work !

image

Can't figure out the right amount of permission

I'm having trouble to figure this out for a couple days, I was hoping you might have some insight:

Running this Invoke-CommandAs -ScriptBlock { Write-Output 'Test'} -AsUser $credObject -verbose as a normal user, returns

Invoke-ScheduledTask : Task was unable to be executed.
At C:\Program 
Files\WindowsPowerShell\Modules\Invoke-CommandAs\3.1.6\public\Invoke-CommandAs.ps1:399 char:17
+                 Invoke-ScheduledTask @Parameters

Fair enough, not every user needs to have permission to create Scheduled Tasks.
When I assign log on as a batch job to the user, no errors comes back, but! I get no Output.

Investigating the $error[0] variable I could see that under hoods there was an error: Get-Job : The command cannot find the job because the job name <GUID> was not found. Verify the value of the Name parameter, and then try the command again.

For now, I only got it working if I add the user to the local Adminstrator group.
Any idea what the exact permissions are?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.