Search code examples
powershellpowershell-2.0powershell-3.0

powershell.exe -ex bypass -command


I have a working powershell script, i Need to convert the entire script to run in single line of code with powershell.exe -ex bypass -command ....

The reason in the background is script should not run as .ps1 file instead i can run as single command. Am looking help in this... am quite new to powershell..but tried to manage the script below.. i need to convert it to run from command as single line of code..

    # Config
$logFileName = "Application" # Add Name of the Logfile (System, Application, etc)
$path = "c:\Intel\" # Add Path, needs to end with a backsplash

# do not edit
$exportFileName = $logFileName + (get-date -f yyyyMMdd) + ".evt"
$logFile = Get-WmiObject Win32_NTEventlogFile | Where-Object {$_.logfilename -eq $logFileName}
$logFile.backupeventlog($path + $exportFileName)

Solution

  • You don't need -ex (short for -ExecutionPolicy) if you're not using a file, because it only applies to files.

    To make it one line, you basically replace newlines with ;.

    But -Command isn't the best idea for this. You're going to have to be careful about properly escaping all the quotes and pipes throughout your code.

    You can look into -EncodedCommand, whereby you Base64 encode your code, and pass it all as one string.

    If you check powershell.exe /? it has an example at the bottom:

    # To use the -EncodedCommand parameter:
    $command = 'dir "c:\program files" '
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
    $encodedCommand = [Convert]::ToBase64String($bytes)
    powershell.exe -encodedCommand $encodedCommand
    

    If you could explain more about your reasons for not wanting to use a file, it may be helpful in getting answers that are more appropriate for your situation.