Powershell:如何读取环境变量?

ary*_*ard 3 powershell

这是我尝试过的第一个powershell脚本.当我运行它时,第一部分运行良好并创建log.txt,但在再次运行后它仍然运行第1部分.如何检查日志文件是否存在?

编辑:我忘了提到我从PowerShell ISE运行脚本,如果这有所作为.

#Variables.
#Set working directory to scripts location.
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath

#Check if log file exists.
$ChkFile = "%userprofile%\Desktop\log.txt" 
$FileExists = (Test-Path $ChkFile -PathType Leaf)

#Set dir to script location.
Set-Location $dir

#Part 1.
If (!($FileExists)) 
{
    Write-Host "Part 1"
    echo 0 >>log.txt
}
#Part 2.
ElseIf ($FileExists)
{
    Write-Host "Part 2"
}
Run Code Online (Sandbox Code Playgroud)

And*_*ndi 7

%用于cmd.exe变量扩展.PowerShell需要不同的语法.而是使用:

 "$env:userprofile\Desktop\log.txt" 
Run Code Online (Sandbox Code Playgroud)

  • Andy是*命令*的亮点,但百分比(%)指标属于不同但虽然志同道合的规则:如果*功能*由cmd.exe实现,那么你必须在PowerShell中找到类似的功能.在这个例子中,`%xyz%`表示cmd.exe下的环境变量,而`$ env:xyz`表示PowerShell中的env var. (2认同)