如何有PowerShell中使用一个else语句搜索
我尝试一些PST文件自动导入到Outlook另一个文件夹,我目前使用下面的脚本如何有PowerShell中使用一个else语句搜索
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
dir “$env:USERPROFILE\appdata\local\microsoft\outlook\.pst” | % {
$namespace.AddStore($_.FullName) }
我想补充一个else语句,以便如果在第一个位置找不到pst文件,那么它将检查“$ env:USERPROFILE \ Documents \ Outlook Files”
对于单个文件,使用Test-Path
来验证文件是否在您期望的位置,例如:
$pathA = "C:\path\to\my\file"
$pathB = "C:\path\to\another\file"
if(Test-Path $pathA){
# do something with $pathA
}
else {
# do something with $pathB
}
在你的情况下,你正在使用dir
(Get-ChildItem
的别名),它返回与指定的路径/名称匹配的文件夹中的所有文件。你可能想要做的就是去寻找文件先在PathA,如果你没有找到任何,看在PathB:
$pathA = "C:\path\to\my\folder\*.pst"
$pathB = "C:\path\to\another\folder\*.pst"
$files = Get-ChildItem $pathA
if($files){
# do something with $pathA
}
else {
# do something with $pathB
}
非常感谢你Charlie! –
对于任何人好奇这是我的新最终脚本
$pathA = “$env:USERPROFILE\AppData\Local\Microsoft\*.pst”
$pathB = “$env:USERPROFILE\Documents\Outlook Files\*.pst”
$files = Get-ChildItem $pathA
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
if($files){
dir “$env:USERPROFILE\AppData\Local\Microsoft\*.pst” | % {
$namespace.AddStore($_.FullName) }
}
else {
dir “$env:USERPROFILE\Documents\Outlook Files\*.pst” | % {
$namespace.AddStore($_.FullName) }
}
再次感谢查理,这是一个很大的帮助!
你可以在if(){...} else {...}块中移动前3个相同的代码行到'if'语句开始之前,因为你将会运行这3行代码,这是一个好的做法,保持代码重复到最小值 –
是否正确? –
是的,这对我来说很合适。找到尽可能多的不同的方式来编写代码来做你想要的程序员所需要的东西,但我会说大多数人会同意在逻辑分支时减少重复的代码行。 –
你的意思是“* .pst”而不是“dir”命令中的“.pst”? –
''''和'''也可能导致问题(与您的路径一致)。使用''',就像在你的第一行一样 – gms0ulman