Invoke-Command is giving NativeCommandError - powershell

I am using Invoke-Command { & "powershell.exe" } -NoNewScope and getting error as belove.
powershell.exe : Loading personal and system profiles took 1761ms.
At line:1 char:18
+ Invoke-Command { & "powershell.exe" } -NoNewScope
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Loading persona...es took 1761ms.:String
) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Error Image

This is...
Invoke-Command { & "powershell.exe" } -NoNewScope
... is for the console host based on your use case.
If you are in the ISE,
... you must use New PowerShell Tab option, to get a new session and your profile will load there.
You can use the shortcut key of course. CRTL+T
Differences between the ISE and PowerShell console - PowerShell Team
Console Application (Non) Support in the ISE
$psUnsupportedConsoleApplications
# Results
<#
wmic
wmic.exe
cmd
cmd.exe
diskpart
diskpart.exe
edit.com
netsh
netsh.exe
nslookup
nslookup.exe
powershell
powershell.exe
ssh-keygen
ssh-keygen.exe
#>
PowerShell- Running Executables - TechNet Articles - United States (English) - TechNet Wiki

Related

Execute a file remotely with powershell

I am trying to run a batch file remotely using Invoke-Command
PS C:\Users\ale> Invoke-Command -ComputerName SERVER -ScriptBlock { Invoke-Expression -Command:"cmd.exe /c 'C:\Test\Extract.bat'" }
The batch file is supposed to output 3 files in C:\Test\ and is running fine locally.
When I execute the command above, here's the output I receive in powershell
NotSpecified: (:String) [], RemoteException
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : SERVER
1_03102021.csv
2_03102021.csv
3_03102021.csv
As I check there was no file in the remote directory. Any advice please?
To call a bat file in powershell where the path has no spaces you can call it directly
PS C:\> c:\temp\bat.bat
If the path/name contains spaces, quote the path and use the command invoke operator &
PS C:\> & "c:\temp\bat with spaces.bat"
So for your command it would be just
Invoke-Command -ComputerName SERVER -ScriptBlock { C:\Test\Extract.bat }

How to run PowerShell Invoke-Command from Command Prompt when the script has a switch?

I have the need to run PowerShell scripts using the command prompt (calling powershell.exe with the -c parameter). I have run these for years but have never tried it with Invoke-Command in order to do remoting and when the script I want to execute has a switch I have to pass.
This piece of code works great from PowerShell, a simple script that has the LogRun switch:
icm -cn MYCOMPUTER02 {C:\Temp\Write-to-File.ps1 -LogRun $Using:LogRun}
However, when I run it via the Command Prompt with powershell.exe fails:
powershell -c "icm -cn MYCOMPUTER02 {C:\Temp\Write-to-File.ps1 -LogRun $Using:LogRun}"
I have tried many variations of this and nothing works, I am sure I missing some syntax detail or some quotes somewhere.
Please let me know if you can help me figure this out.
This is the error I get:
icm : The value of the using variable '$using:LogRun' cannot be retrieved
because it has not been set in the local session.
At line:1 char:1
+ icm -cn MYCOMPUTER02{D:\PatV2DU\PatV2DUService20180411120032\Sc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Command], RuntimeException
+ FullyQualifiedErrorId : UsingVariableIsUndefined,Microsoft.PowerShell.Commands.InvokeCommandCommand

Run a powershell script with different credentials

I'm trying to run a powershell script to search for a network drive for a certain file. In my testing, I've found that my script works perfectly fine, however the network drive I need to search require my Domain Admin logon.
I have
Start-Process powershell.exe -Credential "domain\adminusername" -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"
as the very first line of my script, but whenever I run the script I get this error:
Start-Process : This command cannot be run due to the error: The directory
name is invalid.
At Path\to\script.ps1:1 char:1
+ Start-Process powershell.exe -Credential "domain\adminusername" -NoN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process],
InvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
What directory name is it talking about? If I move the script to the actual network drive, I still get the same error. How do you run a script as a different user?
You could use the net use command to gain access or the new-psdrive command instead. Another option would be to start-process a cmd prompt and use runas within it. Also, you may need to include the full path of powershell.exe or add it to the path variable. %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

Commands gone when using workflow session in powershell

It seems that most common commands are gone when using workflow sessions in powershell:
PS P:\> $session = New-PSWorkflowSession -ThrottleLimit 3
PS P:\> Invoke-Command $session {Write-Output "test"}
The term 'Write-Output' 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 : ObjectNotFound: (Write-Output:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : localhost
What can I do to make all the common commands normally available in workflows available through a session?
Since you are working with a workflow session, you will want to put your commands in a workflow.
$session = New-PSWorkflowSession -ThrottleLimit 3
Invoke-Command $session {
workflow test {
Write-Output -Input "test"
}
test
}
For more info, check out PowerShell Workflows: Restrictions and High Level Architecture of Windows PowerShell Workflow (Part 1)

Powershell: Running a .msc applet as another user

I'm currently writing a powershell script that asks for a single set of admin credentials, and uses those to run relevant applications, pulled from a network-hosted CSV. When I try to run
Start-Process $tools[$userInput-1].path.toString() -credential $credential
(where $tools is returning "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc") I get the error below
Start-Process : This command cannot be executed because the input "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc" is an Invalid Application. Give a valid application and Run your command again.
At line:1 char:14
+ Start-Process <<<< "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc" -credential
Get-Credential
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
If I need to, I'll just write a .bat file and run that, but I'd rather avoid that whenever possible.
And the reason I'm not using Invoke-Item is because it can't take -Credential, even if the man file says otherwise.
.msc is a saved console file, the host of which is mmc, so to start this from powershell you could use syntax similar to the following:
$mmcPath = "C:\Windows\System32\mmc.exe"
$mscPath = "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc"
Start-Process -FilePath $mmcPath -ArgumentList $mscPath