In this simple script, the if
statement works fine when the input file is present, but if the input file is not there it gives me this error and completes:
Get-Content : Cannot find path 'C:\scripts\importfile.txt' because it does not exist.
At C:\Scripts\CLI_Localadmins.ps1:18 char:36
+ If (!($FileExists)) {$Computers = Get-Content -Path 'c:\scripts\importfile.txt'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\scripts\importfile.txt:String) [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand*
this is the code I'm using:
#Check if import file exists.
$ChkFile = "c:\scripts\importfile.txt"
$ValidPath = Test-Path $ChkFile -IsValid
If ($ValidPath -eq $True) {$Computers = Get-Content -Path 'c:\scripts\importfile.txt'
}
Else {$Computers = Get-QADComputer -SizeLimit 0 | select name -ExpandProperty name
}
# Give feedback that something is actually going on
问题出在error语句所述的IF语句中。尝试删除感叹号
I found this website that may help. Here is a quote from the article, "An important warning about using the -isValid switch...since there's nothing syntactically wrong with the path. So Test-Path -isValid $profile will always return true."
I believe the -isValid switch is just checking the syntax of the path and making sure it is correct, it doesn't actually check if the path is there.
Try using split-path instead of -isValid like this
$ValidPath = Test-Path (split-path $ChkFile)
The problem with your condition is that Test-Path $ChkFile -IsValid
checks only if $ChkFile
is a valid path, not if it actually exists. If you want to test for existence you need to remove -IsValid
. Also, I'd recommend using -LiteralPath
, because by default Test-Path
treats the path as a regular expression, which causes problems when a path contains special characters like square brackets.
#Check if import file exists.
$ChkFile = "c:\scripts\importfile.txt"
if (Test-Path -LiteralPath $ChkFile) {
$Computers = Get-Content $ChkFile
} else {
$Computers = Get-QADComputer -SizeLimit 0 | select -Expand name
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.