Trouble creating symlink with semicolon in it from powershell - powershell

So i normally use this syntax to create as symbolic link from powershell.
PS C:\> cmd /c mklink LinkName TargetFolder
However there I'm getting this error when I'm trying to create a symlink with a
semicolon in it.
PS C:\> cmd /c mklink "link;name" "C:\Folder\file;name"
The syntax of the command is incorrect.
If I call it from the cmd application it works fine
C:\>mklink "link;name" "C:\Folder\file;name"
symbolic link created for link;name <<===>> C:\Folder\file;name
Echo args also seems to be working fine when called from cmd via powershell
PS C:\> cmd /c echoargs "link;name" "C:\Folder\file;name"
Arg 0 is <link;name>
Arg 1 is <C:\Folder\file;name>
So why am I not able to create that symlink from powershell. That syntax works with every other legal character, even unicode. Any help would be much appreciated.

Try this:
cmd /c 'mklink "link;name" "C:\Folder\file;name"'

Related

Automate creation of symbolic links on Windows bash

I'm trying to make a script that will do some directory management. The final script will run on Windows and will preferably be written in python. At one point in the script I need to automate the creation of multiple symbolic links between multiple folders. The script itself runs without administrator permissions from a bash terminal (Git Bash). Windows is not in developer mode.
The perfect solution would be to have a list of tuples (link, source) and create the corresponding symbolic links all at once, while having to press "Yes" for administrator rights only once.
I already did some research:
How to create a symlink between directories from inside an elevated cmd: Git Bash shell fails to create symbolic links
mklink /D link source_directory
How to run a command in cmd as an administrator from inside bash: Launch Elevated CMD.exe from Powershell
powershell 'start cmd -v runAs -Args /k, [comma-separated-args]'
How to set the working directory after launching the powershell command as an administrator (Otherwise it launches a terminal from inside C:\Windows\System32\): PowerShell: Run command from script's directory
powershell 'start cmd -v runAs -Args /k, cd, $pwd, "&", [comma-separated-args]'
Let's say I want to create a symbolic link in my current working directory to a relative directory. I tried 2 ways:
When I combine all of the above points and execute the following command from the Git Bash terminal:
powershell 'start cmd -v runAs -Args /k, cd, $pwd, "&", mklink, /D, \"link_to_utils\", \"common\utils\"'
A new terminal opens up (after agreeing for admin rights). But it resulted in a new symlink being created in the root of C:\ .
When I execute this:
powershell 'start cmd -v runAs -Args /k, cd, $pwd
A new terminal opens up (after agreeing for admin rights). I can now run this command:
mklink /D "link_to_utils" "common\utils"
The link is created in the current working directory, as I wanted.
So my questions are:
a) How can I make option 1 work in bash?
b) Why is it actually creating the symlink in C:\?
c) Is there a way to pipe a command into the opened elevated cmd terminal (to make option 2 work)?
Note: I have been trying to find a solution using python and the win32api (pywin32). But that resulted in a bunch of command prompts opening up for each symlink that needs to be created. Also there is barely any documentation regarding pywin32.
Use the following:
powershell 'Start-Process -Verb RunAs cmd /k, " cd `"$PWD`" & mklink /D `"link_to_utils`" `"common\utils`" "'
Since it is PowerShell that interprets that verbatim content of the command line being passed, its syntax rules must be followed, meaning that a "..." (double-quoted) string is required for expansion (string interpolation) of the automatic $PWD variable to occur, and that embedded " characters inside that string must be escaped as `" ("" would work too).
The pass-through command line for cmd.exe is passed as a single string argument, for conceptual clarity.

PSExec and Powershell fails to run a program located in Program Files (x86)

I am struggling to use Psexec inside of a PS script to execute an interactive program.
I have tried this:
PsExec.exe -i \\192.168.100.95 -u Administrador -p Test1234 cmd /c "echo . | powershell notepad" 2> $null
... and it runs perfectly fine. Notepad is launched on a remote machine. Now, when I want to run .exe from Program Files (x86) I get absolutely nothing.
I have tried this variations to run 1.exe located in ProgramFiles(x86):
PsExec.exe -i \\192.168.100.95 -u Administrador -p Test1234 cmd /c "echo . | powershell "${env:ProgramFiles(x86)}\1.exe"" 2> $null
PsExec.exe -i \\192.168.100.95 -u Administrador -p Test1234 cmd /c "echo . | powershell "${env:ProgramFiles(x86)}" + "\1.exe"" 2> $null
However none of them work. Any idea what´s wrong?
Try the following:
psexec cmd /c 'echo . | powershell "& \"${env:ProgramFiles(x86)}\1.exe\"' 2>$null
Note: To better focus on the fundamentals of the solution, I've simplified the psexec command, but the original command should work too.
The entire string passed to cmd /k is single-quoted to prevent PS from interpolating elements up front, notably ${env:ProgramFiles(x86)} whose expansion should be deferred until the command is executed on the target machine.
Note that you normally need a double-quoted string when you pass a command line to cmd /c when invoking from cmd.exe itself. From within PowerShell, however, this is not a requirement: PowerShell first parses the string - whether single- or double-quoted originally - interpolates, if applicable, and then passes the resulting string double-quoted to the external command.
Note the & \"...\" construct in the context of the powershell argument, which ensures that the path with embedded spaces is correctly executed.
Curiously, PS requires " chars. to be escaped as \" when a parameter is passed from the outside world (as opposed to escaping as `" inside the realm of PS).
The command passed to powershell as a whole must be double-quoted, because cmd.exe - in whose context powershell is invoked due to cmd /c - only recognizes double quotes as parameter delimiters and only double quotes protect the enclosed content (mostly) from interpretation.
Why your commands didn't work:
The primary problem was that the executable path that you wanted powershell.exe to invoke ended up containing spaces (C:\Program Files...), causing PowerShell not to recognize the entire path as a single argument. Such a path must be (a) quoted and (b) invoked with &, the call operator.
(In the 2nd attempt, with + ... (string concatenation), you would have had to use & also, and enclose the concatenation in (...)).
For debugging, using cmd /k instead of cmd /c can give you a better sense of how the command is ultimately executed (/k keeps the console window open after execution of the command).
A subtler point is that by using a double-quoted string overall, ${env:ProgramFiles(x86)} was expanded on the source machine rather than on the target machine, where the definition of that environment variable may or may not be the same.
You're putting yourself in Escape Hell by mixing PowerShell, CMD and PsExec. If all you want is run an executable on a remote host, just stick with CMD and PsExec (run the command from CMD too):
PsExec.exe -i \\192.168.100.95 -u Administrador -p Test1234 cmd /c echo. ^| "%ProgramFiles(x86)%\1.exe" 2>nul
That way you just need to escape the pipe (^|) and put the path with spaces in double quotes.

Running CMD command in PowerShell

I am having a bunch of issues with getting a PowerShell command to run. All it is doing is running a command that would be run in a CMD prompt window.
Here is the command:
"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
I have tried the following with no success (I have tried many iterations of this to try and get one that works. Syntax is probably all screwed up):
$TEXT = $textbox.Text #$textbox is where the user enters the PC name.
$CMDCOMMAND = "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"
Start-Process '"$CMDCOMMAND" $TEXT'
#iex -Command ('"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"' $TEXT)
The command will just open SCCM remote connection window to the computer the user specifies in the text box.
Try this:
& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.
It is a much safer way than running batch files!
One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.
PS C:\> "notepad.exe" | cmd
Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.
Edits
CMD's Startup Message is Shown
As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.
For those who may need this info:
I figured out that you can pretty much run a command that's in your PATH from a PS script, and it should work.
Sometimes you may have to pre-launch this command with cmd.exe /c
Examples
Calling git from a PS script
I had to repackage a git client wrapped in Chocolatey (for those who may not know, it's a package manager for Windows) which massively uses PS scripts.
I found out that, once git is in the PATH, commands like
$ca_bundle = git config --get http.sslCAInfo
will store the location of git crt file in $ca_bundle variable.
Looking for an App
Another example that is a combination of the present SO post and this SO post is the use of where command
$java_exe = cmd.exe /c where java
will store the location of java.exe file in $java_exe variable.
You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.
If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

How can I detect whether or not I am in powershell from a command line?

I am creating a standard windows BAT/CMD file and I want to make an IF statement to check whether or not this CMD file is run from PowerShell. How can I do that?
Edit: My underlying problem was that test.cmd "A=B" results in %1==A=B when run from CMD but %1==A and %2==B when run from PowerShell. The script itself is actually run as an old Windows Command line script in both cases, so checking for Get-ChildItem will always yield an error.
One way, it to see what your process name is, and then check its attributes:
title=test
tasklist /v /fo csv | findstr /i "test"
As long as you use a unique name in place of Test, there should be little room for error.
You will get back something like:
"cmd.exe","15144","Console","1","3,284
K","Running","GNCID6101\Athomsfere","0:00:00","test"
When I ran the above code from a bat file, my output was:
"powershell.exe","7396","Console","1","50,972
K","Running","GNCID6101\Athomsfere","0:00:00","
A potentially simpler approach that may work for you. If not, it may be suitable for others.
Create 2 separate script files: test.ps1 and test.cmd
Don't include extension when calling the script. I.e. call as <path>\test (or just test if folder is in the path environment variable.
This works because CMD prioritises which script to execute as: .bat > .cmd, whereas Powershell prioritises: .ps1 > .bat > .cmd.
The following is the output of a CMD session:
C:\Temp>copy con test.cmd
#echo cmd^Z
1 file(s) copied.
C:\Temp>copy con test.ps1
Write-Output "ps1"^Z
1 file(s) copied.
C:\Temp>.\test
cmd
C:\Temp>
And calling test from Powershell:
PS C:\Temp> .\test
ps1
PS C:\Temp>
Couldn't you try to execute a Get-ChildItem and then check %ERRORLEVEL% to see if it returns an exe not found?
http://ss64.com/nt/errorlevel.html

PowerShell alias syntax for running a cmd.exe builtin function?

As I have only recently switched to PowerShell from cmd.exe, I often find it convenient to do little things in a familiar way by calling cmd to do them. For instance, to do a 'bare' file listing this works great:
PS> cmd /c dir /b
dir1
dir2
file1.txt
I'd like to make an alias for this but I can't figure out the right syntax. So far I've tried:
PS> Set-Alias dirb cmd /c dir /b # error (alias not created)
PS> Set-Alias dirb "cmd /c dir /b" # fail (alias doesn't work)
PS> Set-Alias dirb "cmd `"/c dir /b`"" # fail (alias doesn't work)
Any suggestions? I'm looking for a general solution to calling builtin cmd.exe commands (such as dir). I'd also like to know how to produce bare output the right way using PowerShell cmdlets, but that's a secondary concern at the moment. This question is about the proper syntax for calling cmd.exe from an alias.
I believe what you want is a function, not an alias. For instance:
function dirb {
cmd /c dir $args[0] /b
}
From a PS prompt, run notepad $profile, paste that into your profile and then it will load automatically when you open a PS console and you can do this:
dirb c:\somedir
See get-help about_functions for more information about functions.
Aliases are not designed for this kind of tasks. An alias is just another name of a command. Use the function instead.
function dirb { cmd /c dir /b }
Aliases in powershell don't take parameters unfortunately - you need to define a function for this. For more info,
get-help aliases
Why on earth would you use powershell to open the command prompt? That seems to be defeating the purpose.
The Alias I prefer to list out files is simply ls