1
这是我尝试的第一个PowerShell脚本。当我运行它时,第一部分运行良好并创建log.txt,但是在再次运行它之后,它仍然运行第1部分。如何检查日志文件是否存在?Powershell:如何读取环境变量?
编辑:我忘了提及,如果这有所作为我正在从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"
}
谢谢。这解决了它。所有的cmd.exe命令都不能在PowerShell中工作吗? – arynhard
同样可以用%windir% - > $ env来完成:windir ?? – arynhard
@AndrewRynhard如果该命令是使用cmd.exe实现的,那么它将不能在PowerShell中运行,除非通过'&cmd.exe/c调用它。如果该命令实际上是像'xcopy'这样的命令行程序,它在PowerShell中可以正常工作。 –