Home > Software design >  Issue with executing Powershell commands in .ps1 from windows command prompt using powershell.exe
Issue with executing Powershell commands in .ps1 from windows command prompt using powershell.exe

Time:07-01

I am facing issue when executing powershell commands written in .ps1 file in windows command tool (cmd.exe). Below is how i am trying to execute

  1. Open command prompt
  2. Execute powershell -> C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -file C:\Users\Usha\Desktop\foldername\powershellfile.ps1

The powershell file (powershellfile.ps1) has below lines of code

$jsonStr = Get-Content -Raw -Path C:\Users\Usha\Desktop\foldername\filename.json | ConvertFrom-JSON
New-Item -Path 'D:\ps' -Name 'testfile.txt' -ItemType 'file'

But it gives below error Get-Content : A parameter cannot be found that matches parameter name 'Raw'

If i remove the 1st like line, it gives error to 2nd line when creating file as below Out-file : Cannot find drive. A drive with name ''c' doesnot exist.

Here i am giving location as c:\users\desktop\foldername

The script works fine when running in windows powershell. But this only exists when running using powershell.exe as above.

I am unable to understand how to fix as everywhere in internet it is told to execute by invoking powerhsell.exe

Please help me to fix this issue.

Thanks in advance, Usha. Please help me

CodePudding user response:

Your question title says commands but your poorly-formatted code suggests you're passing a file.

Which is it?

How to call a file:

powershell.exe -file "C:\path\to\file.ps1"
# or
powershell.exe -file "C:\path\to\file.ps1" -param value

How to run a command:

powershell.exe -command "get-date; whoami"
# or
powershell.exe -c "& {get-date; 'a string'; "another complicated string$(Get-random @('!','?','.'))" }"

OR....

RTFM powershell.exe /?


Friendly Tip:
You would better comprehend the right method if you create a simple script with just $env:username, figure out how to execute that, then try your script.

CodePudding user response:

I can recreate this error in powershell 2.0. You will need 3 or later to use the raw parameter to get-content. Check your version using the variable $psversiontable

Or you can consider why you are using the raw parameter and if you really need it.

  • Related