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

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

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 }

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

How do I run a *.exe file from PowerShell

I have a folder at C:\Folder that has files input.xml, output.xml and licensegenerator.exe. Licensegenerator.exe takes variables that we put into input.xml and creates a temporary license for one of our programs using the output.xml file. We typically do this via command line by navigating to the C:\Folder directory, then running the command:
LicenseGenerator.exe "C:\Folder\input.xml" "C:\Folder\output.xml"
I'm attempting to write a script to do the exact same thing in PowerShell, but I'm struggling... Here's what I have:
$inputtest = "C:\Folder\Input.xml"
$outputtest = "C:\Folder\Output.xml"
$licensegen = "C:\Folder\LicenseGenerator.exe"
Invoke-Command $licensegen "$inputtest" "$outputtest"
When I run this, I get the error:
Invoke-Command : A positional parameter cannot be found that accepts argument
'C:\Folder\Output.xml'.
At line:5 char:1
+ Invoke-Command $licengegen "$inputtest" "$outputtest"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
I have also tried running with Invoke-Expression but get the exact same error (except it says "Invoke-Expression" at the beginning). Anybody have any idea what I'm doing wrong here?
You're looking for the call operator (&):
& $licensegen "$inputtest" "$outputtest"
Invoke-Command is essentially for running scriptblocks on other hosts and/or in other user contexts.
Start-Process
is great because you can runas, redirect output, hide the child processes window and much more.
Start-Process -FilePath $licensegen -Argumentlist $inputtest,$outputtest
& "[path] command" [arguments]
Just replace Invoke-Command with &

Set the font type and size using the command prompt (or batch file)

I tried the solution given from: Specify the size of command prompt when executing a batch file
I ran:
powershell -command "&{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But I get these errors, any ideas?
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. At line:1 char:22 + &{set-executionpolicy <<<< remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
Import-Module : The specified module 'SetConsoleFont' was not loaded because no valid module file was found in any module directory . At line:1 char:50 + &{set-executionpolicy remotesigned; Import-Module <<<< SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : ResourceUnavailable: (SetConsoleFont:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
The term 'Get-ConsoleFontInfo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spe lling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:86 + &{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo <<<< | Format-Table -AutoSize} + CategoryInfo : ObjectNotFound: (Get-ConsoleFontInfo:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
I have put the file SetConsoleFont.psm1 in
C:\Users\Adrian\Documents\WindowsPowerShell\Modules\SetConsoleFont
You say "You're not allowed to set the execution policy" well maybe I'm not, but it's my machine so why shouldn't I? I don't want to execute these commands as Administrator, just as a user, me (Adrian)
Another comment was to try set-executionpolicy bypass process
so I tried:
powershell -command "&{set-executionpolicy bypass process; set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But got even more red errors.
I have no idea what powershell is or how to use it, I just want to change the font from a batch file without hassle!
Try set-executionpolicy bypass process instead.
Also make sure you have put the module in a module path folder such as:
[yourprofile]\Documents\WindowsPowershell\Modules
I managed to get it working but only in a PowerShell console, and I had to run it as Administrator. However this is not practical for me for the following reasons:
I wish to change the font of new window seamlessly from a batch file, which will be run by users of the software. They may not have Administrator access and so cannot execute "set-executionpolicy remotesigned" which I needed to do to get it working.
Also this has to be done in a DOS batch file, so opening up a powershell window is not an option. It only works in a PowerShell window and not with the DOS "powershell -command" option.
So a partial answer.
If you want to change Execution Policy, it should be done in an elevated prompt.
And loading the module can be done by giving absolute path. Example is below.
Import-Module c:\users\testuser\desktop\SetConsoleFont.psm1 -Verbose
and we can bypass execution policy like below.
powershell.exe -executionpolicy bypass -command "${<your code>}"
Edit: The imported module will be available only in the scope of the script block.
here it is with in {}. So whatever cmdlets and functions in side the module should be executed in sided the scriptblock.
Regards,
Kvprasoon

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