2012-05-31 127 views
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" 
} 

回答

5

%爲cmd.exe的變量擴展。您需要PowerShell的不同語法。相反使用:

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

謝謝。這解決了它。所有的cmd.exe命令都不能在PowerShell中工作嗎? – arynhard

+0

同樣可以用%windir% - > $ env來完成:windir ?? – arynhard

+1

@AndrewRynhard如果該命令是使用cmd.exe實現的,那麼它將不能在PowerShell中運行,除非通過'&cmd.exe/c 調用它。如果該命令實際上是像'xcopy'這樣的命令行程序,它在PowerShell中可以正常工作。 –