【问题标题】:Powershell: how to read an environment variable?Powershell:如何读取环境变量?
【发布时间】:2013-11-15 23:38:02
【问题描述】:

这是我尝试的第一个 powershell 脚本。当我运行它时,第 1 部分运行良好并创建了 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"
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

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

     "$env:userprofile\Desktop\log.txt" 
    

    【讨论】:

    • 谢谢。那解决了它。是不是所有的 cmd.exe 命令都不能在 powershell 中运行?
    • @AndrewRynhard 如果该命令是使用 cmd.exe 实现的,那么它将无法在 PowerShell 中运行,除非您通过 & cmd.exe /c <DOS COMMAND HERE> 调用它。如果该命令实际上是像xcopy 这样的命令行程序,它将在 PowerShell 中正常工作。
    • Andy 擅长命令,但百分比 (%) 指标属于不同但志同道合的规则:如果 功能 由 cmd.exe 实现,那么你必须在 PowerShell 中找到类似的功能。在本例中,%xyz% 表示 cmd.exe 下的环境变量,而$env:xyz 表示 PowerShell 中的同一个 env var。
    • @msorens 实际上你可以传入 cmd.exe 操作符。试试这些:& cmd.exe /c echo '%userprofile%\Desktop\log.txt'& cmd.exe /c dir '"%ProgramFiles%"' '&' dir '"%windir%"'。它们只是作为字符串发送到 cmd.exe,它会在运行时评估它们。
    猜你喜欢
    • 1970-01-01
    • 2015-05-18
    • 2018-07-01
    • 2017-09-04
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2019-07-27
    相关资源
    最近更新 更多