Powershell script cannot recognize absolute file path - powershell

I have a windows command script that needs to run another powershell script in another location. The windows command script contains the following code:
powershell -NoProfile -Command "Set-ExecutionPolicy Bypass -Scope Process -Force; & "C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1" -Update"
When I run the windows command script, it always show the following error:
& : The term 'C:\Users\Tommy' 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.
At line:1 char:53
I have tried adding dot to the front of the absolute file path and it did not work.

Try updating "C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1" to 'C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1'. You are ending your quotes early by using the double quotes again.
powershell -NoProfile -Command "Set-ExecutionPolicy Bypass -Scope Process -Force; & 'C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1' -Update"

Related

How to create a Powershell Alias for Set-Executionpolicy

Following guides to create an alias in powershell, I have run the following command:
Set-Alias rush-enable "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass"
This sets the alias. However when I run the alias I hit an error.
PS C:\example> rush-enable
rush-enable : The term 'Set-ExecutionPolicy -Scope Process
-ExecutionPolicy Unrestricted' 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.
At line:1 char:1
+ rush-enable
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Set-ExecutionPo.
..cy Unrestricted:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
However running the command on it's own works fine:
PS C:\example> Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted
PS C:\example>
Am I missing something? How should I format the command to work as an alias?
As per the documentation:
You can assign an alias to a cmdlet, script, function, or executable
file.
You cannot assign an alias to a command and its parameters. For
example, you can assign an alias to the Get-Eventlog cmdlet, but you
cannot assign an alias to the Get-Eventlog -LogName System command.
This is presumably a way to avoid having to disambiguate a parameter that exists on an alias and which is passed when invoking the alias.
You therefore have two options:
Encapsulate your command in a function called Enable-Rush (note the PowerShell acceptable naming scheme, if you care). In your case this would look something like:
function Enable-Rush {
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
}
Save the command as a file and create a alias to the file.
And to persist it, put it in a $PROFILE. Depending on your system, you might need to digitally sign the $PROFILE or change the PowerShell system Execution Policy to allow PowerShell scripts generated by the system to execute when starting a PowerShell process.

Line breaks invoking PowerShell from MSBuild

I'm trying to call a PowerShell script from my MSBuild script. When I collapse the following into a single line, it runs, but when I leave it like this, I get the error below. In case it matters, I'm kicking off the MSBuild script from a BAT script.
<Exec Command="powershell.exe -NonInteractive -ExecutionPolicy Unrestricted
-Command "& Invoke-Command
-ComputerName &apos;$(Server)&apos;
-ScriptBlock {
&install.ps1
-serviceName &apos;$(ServiceName)&apos;
-exePath &apos;$(ExePath)&apos;
-computerName &apos;$(Server)&apos;
} "
" />
'-Command' is not recognized as an internal or external command,
operable program or batch file.
'-ComputerName' is not recognized as an internal or external command,
operable program or batch file.
'-ScriptBlock' is not recognized as an internal or external command,
operable program or batch file.
& was unexpected at this time.
I copied the XML from Microsoft documentation as a starting point, I checked that all whitespace are plain space characters, I tried adding a space to the end of each line, I tried making sure there was only a single space at the beginning of each line with none at the end, and I tried both Windows and Unix line endings. None of those made any difference, so I'm not sure what could be happening.
After some feedback, I've tried adding ` and ^ to the end of each line except the one with />, and neither allowed the script to run.
Thanks to #PetSerAl's comments, I was able to fix it like so, by adding ^ at the end of each line, and before each double-quot and ampersand:
<Exec Command="powershell.exe -NonInteractive -ExecutionPolicy Unrestricted ^
-Command ^"^& Invoke-Command
-ComputerName &apos;$(Server)&apos; ^
-ScriptBlock { ^
^&install.ps1 ^
-serviceName &apos;$(ServiceName)&apos; ^
-exePath &apos;$(ExePath)&apos; ^
-computerName &apos;$(Server)&apos; ^
} ^"
" />

How to pass path with spaces to script

I am trying to use PowerShell to call an EXE that is at a location/path containing spaces. When I call the script from the command line, the EXE's full path is not being passed to the script. Any ideas as to why this is happening?
PowerShell Script Contents (Untitled1.ps1)
Here is the entire script that gets called from the command line:
param(
[string] $ParamExePath
)
function Run-CallThisExe {
param(
[string] $ThisExePath
)
Write-Host "ThisExePath: " "$ThisExePath"
start-process -FilePath $ThisExePath
}
write-host "ParamExePath: " $ParamExePath
Run-CallThisExe -ThisExePath "$ParamExePath"
Command Line String
Here is the command line string being run from the PowerShell script's parent folder:
powershell -command .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"
Output
Here is what is output after running the script
ParamExePath: C:\path
ThisExePath: C:\path
start-process : This command cannot be run due to the error: The system cannot
find the file specified.
At C:\sample\Untitled1.ps1:11 char:5
+ start-process -FilePath $ThisExePath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Just change this:
powershell -command .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"
To This:
powershell -file .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"
The -Command Parameter used to execute commands for example {Get-Date}
The -File Parameter used to Run .ps1 Script File
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
Type Powershell /? to get full details on each Parameter
A couple of other ways to call it:
powershell -command .\Untitled1.ps1 -NonInteractive "-ParamExePath 'C:\path with spaces\myapp.exe'"
powershell -command ".\Untitled1.ps1 -ParamExePath 'C:\path with spaces\myapp.exe'" -NonInteractive
Note that if you pass a folder path to Powershell that has a trailing backslash it cannot handle it. e.g. -ParamFolder "C:\project folder\app\bin debug\". The parameter string ends up with a double quote at the end. So when you try to append the name of a file to it you end up with something like C:\project folder\app\bin debug"Filename.txt. In this case you have to send in a second backslash at the end.

Powershell opening file path with whitespaces

I'm my PS script I want to be able to run another script in another PS instance by doing the following:
$filepath = Resolve-Path "destruct.ps1"
start-process powershell.exe "$filepath"
destruct.ps1 is in the same folder as this script.
However when running this script in a location which includes spaces ("C:\My Scripts\") I will get the following error:
The term 'C:\My' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.
I know by using a '&' with the Invoke-Expression method solves this problem, how can I do the same but by using the start-process method?
try this:
start-process -FilePath powershell.exe -ArgumentList "-file `"$filepath`""
edit after comments:
start-process -FilePath powershell.exe -ArgumentList "-file `"$($filepath.path)`""
side note:
$filepath is a [pathinfo] type and not a [string] type.
You can add escaped double quotes so that you pass a quoted argument:
"`"$filepath`""
I am answering here for a general scenario.
If you need to navigate to a folder for example C:\Program Files from the Powerhsell, the following command won't work as it has white space in between the path.
cd C:\Program Files
Instead embed the path with double quotes as like the below.
cd "C:\Program Files"
File name might contain spaces, so preserve spaces in full path:
Notepad++ exec command:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" "& \"$(FULL_CURRENT_PATH)\""
same from command prompt:
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" "& \"C:\a_work\Systems\name with spaces.ps1\""
Just in case [string]$shipno (which is path & file name) comes in including spaces the following allows it to be passed to -FilePath successfully:
if ($shipno.contains(" ") -eq $true) {
$shipno = """" + $shipno + """"
}

Run PowerShell command from command prompt (no ps1 script)

I'm looking for a way to run just a couple PowerShell commands from the command prompt. I don't want to create a script for this since it's just a couple commands I need to run and since I don't really know how to script with PowerShell.
Here is the command I'm trying to use to start with:
Get-AppLockerFileInformation -Directory <folderpath> -Recurse -FileType <type>
I don't really want to create a script for this as it would be much easier if I can just run one or two commands from a batch file with the rest of the stuff.
EDIT:
Here is what I've tried so far.
1)
powershell -Command "Get-AppLockerFileInformation....."
Error: The term 'Get-AppLockerFileInformation is not recognized as the name of a cmdlet, function, script file, or operable program....
2)
powershell -Command {Get-AppLockerFileInformation.....}
No error with this way but I don't get anything back. If I use the Set-AppLockerPolicy... nothing happens.
3)
powershell -Command "{Get-AppLockerFileInformation.....}"
Error: The term 'Get-AppLockerFileInformation is not recognized as the name of a cmdlet, function, script file, or operable program....
4)
powershell -Command "& {Get-AppLockerFileInformation.....}"
Error: The term 'Get-AppLockerFileInformation is not recognized as the name of a cmdlet, function, script file, or operable program....
5)
powershell "& {Get-AppLockerFileInformation.....}"
Error: The term 'Get-AppLockerFileInformation is not recognized as the name of a cmdlet, function, script file, or operable program....
6)
powershell -ExecutionPolicy Bypass -NoLogo -NoProfile -Command {Get-AppLockerFileInformation....}
No error but nothing happens.
7)
powershell -ExecutionPolicy Bypass -NoLogo -NoProfile -Command "Get-AppLockerFileInformation...."
No error but nothing happens.
Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).
powershell -command "& {&'some-command' someParam}"
Also, here is a neat way to do multiple commands:
powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"
For example, this is how I ran my 2 commands:
powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"
Run it on a single command line like so:
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile
-WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath>
-Recurse -FileType <type>"
Maybe powershell -Command "Get-AppLockerFileInformation....."
Take a look at powershell /?
This works from my Windows 10's cmd.exe prompt
powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"
This example shows
how to chain multiple commands
how to import module with module path
how to run a function defined in the module
No need for those fancy "&".