%temp% etc not working - powershell

I have the below that is used as a batch file that launches powershell (too long to go over but it is used in another script).
Anyway, I noticed the %systemroot%\temp and %systemroot% does not work.
Any idea how I can fix this?
%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File %SystemRoot%\TEMP\ROFS\testing_script_log.ps1
Thanks,

If you are executing that line from PowerShell rather than from CMD, you can use the PowerShell environment variable syntax:
PS C:\> & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"

You can use [Environment]::ExpandEnvironmentVariables to expand environment variables within a string the old-fashioned way.
$s = '%systemroot%\temp'
[Environment]::ExpandEnvironmentVariables($s)

Successfully verified with below code C#.
//file location - User Variables
string fileLocation = Environment.GetEnvironmentVariable("AZURE_FILE_PATH", EnvironmentVariableTarget.User);
//file location - System Variables
string fileLocation = Environment.GetEnvironmentVariable("AZURE_FILE_PATH", EnvironmentVariableTarget.Machine);
On Powershell script
& "D:\Visual_Studio_Workspace\AzureUpload\AzureUpload\bin\Debug\AzureUpload.exe"
AzureUpload.exe -- contain the above code C# code as Console application (Visual_Studio_Workspace\AzureUpload\AzureUpload\bin\Debug{.exe file location})

Related

Powershell file download issue

I'm trying to download the PuTTY executable using PowerShell, but could not get the file on temp path.
My script:
$Url = "https://the.earth.li/~sgtatham/putty/latest/x86/putty.exe"
$Path = "C:%homepath%\AppData\Local\Temp\putty.exe"
$Wc = New-Object System.Net.WebClient
$Wc.DownloadFileAsync($Url,$Path)
I am executing following command via CMD:
powershell.exe "-ExecutionPolicy" "RemoteSigned" "-file" "test.ps1"
You have two problems, both of which need to be corrected for your script to have a chance of working.
The command for executing a Powershell script from within CMD.EXE should not have the arguments quoted:
powershell.exe -ExecutionPolicy RemoteSigned -file test.ps1
To expand a system environment variable from within powershell, you do not surround it with % as you do in CMD. See http://ss64.com/ps/syntax-env.html for more information; assuming that the environment variable HOMEPATH exists, you would reference it in Powershell as $env:homepath, not %homepath%.
The %VAR% form is not used in powershell, this is only used in CMD. In PowerShell you need to use $env:VAR instead.
You can run Get-ChildItem Env: to get a list of all the Environmental Variables you can use.
For your script try this:
$Path = "$env:USERPROFILE\AppData\Local\Temp\putty.exe"
I've used USERPROFILE instead of HOMEPATH as this includes the drive letter so your script will still work if a different letter is used.

Getting Script name in Powershell

Is there any other way except $MyInvocation.InvocationName in powershell to get the script name?
As i need to turn my script in an exe and in that case it doesnt work on that exe.
I'm assuming since you convert the powershell script to an executable that you are after the location of the executable. You can get it this way:
[Environment]::GetCommandLineArgs()[0]
If you want something that works within and outside of ISE you can use
$MyInvocation.InvocationName
Since full paths and .\YourScript.ps1 can be returned you can parse the name with:
[Regex]::Match( $MyInvocation.InvocationName, '[^\\]+\Z', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [System.Text.RegularExpressions.RegexOptions]::SingleLine ).Value

How do I write this in Powershell script?

I am very new to Powershell script.
I am trying to run a powershell script from a cmd
powershell.exe Set-ExecutionPolicy Unrestricted
powershell.exe .\startup.ps1
I need two lines within powershell script.
%WINDIR%\system32\inetsrv\appcmd.exe add apppool /name:"VCPool" /managedRuntimeVersion:"v4.0" /managedPipelineMode:"Integrated"
%WINDIR%\system32\inetsrv\appcmd.exe set app "WebRole_IN_0_VC/" /applicationPool:"VCPool"
Can I simply write it like this within the ps1 file?
& %WINDIR%\system32\inetsrv\appcmd.exe add apppool /name:"VCPool" /managedRuntimeVersion:"v4.0" /managedPipelineMode:"Integrated"
Many Thanks
Short answer, including a question: Why the hell does that need to be a PowerShell script?
You can simply create a batch file containing
%WINDIR%\system32\inetsrv\appcmd.exe add apppool /name:"VCPool" /managedRuntimeVersion:"v4.0" /managedPipelineMode:"Integrated"
%WINDIR%\system32\inetsrv\appcmd.exe set app "WebRole_IN_0_VC/" /applicationPool:"VCPool"
and run that directly instead of trying to figure out execution policies, etc.
Furthermore, appcmd should probably be in your PATH, so you can run it directly without needing to specify the full path to the program.
Longer answer, actually using PowerShell: There are two problems here.
You want to run a PowerShell script without having the appropriate execution policy set. This can be done with
powershell -ExecutionPolicy Unrestricted -File myscript.ps1
You need to adjust environment variable usage within PowerShell scripts, as % is not used to expand environment variables there. So you actually need
& $Env:WinDir\system32\inetsrv\appcmd.exe add apppool /name:VCPool /managedRuntimeVersion:v4.0 /managedPipelineMode:Integrated
& $Env:WinDir\system32\inetsrv\appcmd.exe set app WebRole_IN_0_VC/ /applicationPool:VCPool
Note also that you need an ampersand (&) before each line as a variable name in the beginning of a line switches into expression mode while you want to run a command, therefore needing command mode.
Furthermore quoted arguments can be a bit of a pain in PowerShell. PowerShell tries quoting arguments when necessary and it's not always obvious when things go wrong what actually comes out on the other end. In this case the easiest way is to not quote the arguments in any way whcih ensures that they come out correctly:
PS Home:\> args add apppool /name:VCPool /managedRuntimeVersion:v4.0 /managedPipelineMode:Integrated
argv[1] = add
argv[2] = apppool
argv[3] = /name:VCPool
argv[4] = /managedRuntimeVersion:v4.0
argv[5] = /managedPipelineMode:Integrated
PS Home:\> args set app WebRole_IN_0_VC/ /applicationPool:VCPool
argv[1] = set
argv[2] = app
argv[3] = WebRole_IN_0_VC/
argv[4] = /applicationPool:VCPool
However, if appcmd actually needs the quotes around the argument after a colon, then you need to quote the whole argument with single quotes and add the double quotes back in:
& $Env:WinDir\system32\inetsrv\appcmd.exe set app WebRole_IN_0_VC/ '/applicationPool:"VCPool"'
You might like to know you can combine the two launch statements into a single call within your CMD file:
powershell.exe -noprofile -executionpolicy unrestricted -file .\startup.ps1
The only slightly strange thing about calling appcmd.exe from PowerShell is you must surround the parameter in quotes, even if it contains no spaces. You have already done this, so yes it should work.

Powershell.exe running the script in cli, or a wrapper?

I have a third-party application that's extensible by adding exe-files that perform dataconversion etc. I've written an extension in Powershell that does the conversion I want, but I'm unable to get the third-party app to run my ps1, as it will only accept an .exe file as an extension.
The app adds a filename as the first (and only) commandline argument to the extension, so the command it runs looks like:
someprogram.exe somefile.xml
I tried to get it to run Powershell.exe with my script as an argument, but I haven't been able to figure out how and if that's possible. Some stuff I tried like
powershell.exe myscript.ps1
won't work. I tried getting the script to find the correct XML file itself, but still somehow I couldn't get Powershell to run off the commandline and take a script as an argument and run it.
Next I thought about writing a small .exe file that only runs the Powershell script, but is that even possible? If it is, could someone nudge me in the right direction?
Powershell wants to have a qualified path to script files before it will run them. So you need to either use
powershell.exe .\myscript.ps1
if it lies in the current working directory (unlikely and prone to break for this use case) or use the full path to the script:
powershell.exe C:\Users\Foo\Scripts\myscript.ps1
or similar.
You can also try Powershell.exe -Command "& your-app.exe ${your-arguments}

Set up PowerShell Script for Automatic Execution

I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:
One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)
A file that I can double-click to run the above (I would use this method when manually testing components of my build process)
I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.
From http://blogs.msdn.com/b/jaybaz_ms/archive/2007/04/26/powershell-polyglot.aspx
If you're willing to sully your beautiful PowerShell script with a little CMD, you can use a PowerShell-CMD polyglot trick. Save your PowerShell script as a .CMD file, and put this line at the top:
#PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=#(^&{$args} %*);'+[String]::Join(';',(Get-Content '%~f0') -notmatch '^^#PowerShell.*EOF$')) & goto :EOF
If you need to support quoted arguments, there's a longer version, which also allows comments. (note the unusual CMD commenting trick of double #).
##:: This prolog allows a PowerShell script to be embedded in a .CMD file.
##:: Any non-PowerShell content must be preceeded by "##"
##setlocal
##set POWERSHELL_BAT_ARGS=%*
##if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:"=\"%
##PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=#(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join(';',$((Get-Content '%~f0') -notmatch '^^##'))) & goto :EOF
Save your script as a .ps1 file and launch it using powershell.exe, like this:
powershell.exe .\foo.ps1
Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least "RemoteSigned" so that unsigned local scripts can be run.
Run Script Automatically From Another Script (e.g. Batch File)
As Matt Hamilton suggested, simply create your PowerShell .ps1 script and call it using:
PowerShell C:\Path\To\YourPowerShellScript.ps1
or if your batch file's working directory is the same directory that the PowerShell script is in, you can use a relative path:
PowerShell .\YourPowerShellScript.ps1
And before this will work you will need to set the PC's Execution Policy, which I show how to do down below.
Run Script Manually Method 1
You can see my blog post for more information, but essentially create your PowerShell .ps1 script file to do what you want, and then create a .cmd batch file in the same directory and use the following for the file's contents:
#ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'"
Replacing MyPowerShellScript.ps1 on the 3rd line with the file name of your PowerShell script.
This will allow you to simply double click the batch file to run your PowerShell script, and will avoid you having to change your PowerShell Execution Policy.
My blog post also shows how to run the PowerShell script as an admin if that is something you need to do.
Run Script Manually Method 2
Alternatively, if you don't want to create a batch file for each of your PowerShell scripts, you can change the default PowerShell script behavior from Edit to Run, allowing you to double-click your .ps1 files to run them.
There is an additional registry setting that you will want to modify so that you can run scripts whose file path contains spaces. I show how to do both of these things on this blog post.
With this method however, you will first need to set your execution policy to allow scripts to be ran. You only need to do this once per PC and it can be done by running this line in a PowerShell command prompt.
Start-Process PowerShell -ArgumentList 'Set-ExecutionPolicy RemoteSigned -Force' -Verb RunAs
Set-ExecutionPolicy RemoteSigned -Force is the command that actually changes the execution policy; this sets it to RemoteSigned, so you can change that to something else if you need. Also, this line will automatically run PowerShell as an admin for you, which is required in order to change the execution policy.
Source for Matt's answer.
I can get it to run by double-clicking a file by creating a batch file with the following in it:
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe LocationOfPS1File
you can use this command :
powershell.exe -argument c:\scriptPath\Script.ps1