$filepath = "c:\InstacartImages\"
$mainDIRoutput = (Test-Path $filepath) | Out-String
if($mainDIRoutput -eq 'False'){
write-host ("This is the if Statment")
}
else {
write-host ("This is the else statment")
}
似乎每次运行此代码时,无论是否存在正确的路径,它总是转到else语句。不知道我在想什么。
您可以像这样简单地使用布尔值:
$filepath = "c:\InstacartImages\"
$mainDIRoutput = Test-Path $filepath
if($mainDIRoutput)
{
write-host ("This is the if Statment")
}
else {
write-host ("This is the else statment")
}
详细阐述@Mathias R. Jessen的建议。Test-Path
返回布尔值True或False,由相应的变量$true
和$false
表示。话虽如此,您可以尝试:
if($mainDIRoutput -eq $false){
write-host ("This is the if Statment")
}
else {
write-host ("This is the else statment")
}
因此,如果返回$mainDIRoutput = $false
,则返回$mainDIRoutput = $true
。
我玩了Out-String
,引起了我的注意:
$true
True
但是
($true | out-string) -eq 'true'
False
如前所述$true
返回true的值,它是4个字符,但是如果我们使用Out-string
,它将返回6个字符:
($true | out-string).Length
6
出于好奇,我将其转换为ASCII,因为最后两个符号为空:
($true | out-string).ToCharArray() | foreach {[int][char]$_}
84
114
117
101
13
10
84 = T,114 = r,117 = u,101 = e,13 =回车,10 =换行。
如果仍然需要使用字符串而不是布尔值,则可以尝试
($true).ToString().length
4
和
($true).ToString() -eq 'true'
True
或您的情况:
$mainDIRoutput = (Test-Path $filepath).tostring()
希望有帮助。
使用穷人的调试方法,通过使用PowerShell变量压缩来同时分配给变量和输出
($filepath = 'd:\temp\')
($mainDIRoutput = Test-Path $filepath | Out-String)
if ($mainDIRoutput -eq 'False') { 'This is the if Statment' }
else { 'This is the else statment' }
# Results
<#
d:\temp\
True
This is the else statment
#>
($filepath = 'd:\temp\')
($mainDIRoutput = Test-Path $filepath)
if ($mainDIRoutput -eq 'False') { 'This is the if Statment' }
else { 'This is the else statment' }
# Results
<#
d:\temp\
True
This is the if Statment
#>
($filepath = 'd:\temp\')
($mainDIRoutput = Test-Path $filepath | Out-String)
if ($mainDIRoutput) { 'This is the if Statment' }
else { 'This is the else statment' }
# Results
<#
d:\temp\
True
This is the if Statment
#>
($filepath = 'd:\temp\')
($mainDIRoutput = Test-Path $filepath)
if ($mainDIRoutput) { 'This is the if Statment' }
else { 'This is the else statment' }
# Results
<#
d:\temp\
True
This is the if Statment
#>