這是Powershell腳本的一小塊,爲了遞歸獲取所有文件夾/子文件夾和文件,我不能使用Get-ChildItem
,因爲它在UNC網絡路徑上速度太慢,所以我的想法是使用使用PSSession遠程執行[Microsoft.VisualBasic.FileIO.FileSystem]::GetFiles
,並且它工作。Try Catch statement is breaking my code
通過使用PsSession遠程執行此代碼,我的try/catch語句完美運行,我可以將結果變爲$GetRemoteFolderCheck
變量。
$path_folder = "C:\sources\sql"
$session = New-PSSession -ComputerName $ipsqlserver -Credential $credentials
Invoke-Command -Session $session -ScriptBlock {
[reflection.assembly]::loadwithpartialname("Microsoft.VisualBasic") | Out-Null
}
$GetRemoteFolderCheck = Invoke-Command -Session $session -ScriptBlock {
try
{
[Microsoft.VisualBasic.FileIO.FileSystem]::GetFiles(
$using:path_folder,
[Microsoft.VisualBasic.FileIO.SearchOption]::SearchAllSubDirectories)
}
catch
{
return $_
}
}
但是,當我在本地執行相同的代碼,而無需使用PSSession時,它不工作,它打破我的代碼......因爲Write-Host
沒有在我的殼顯示
$path_folder = "C:\sources\sql"
$GetLocalFolderCheck = try{[Microsoft.VisualBasic.FileIO.FileSystem]::GetFiles(
$path_folder,
[Microsoft.VisualBasic.FileIO.SearchOption]::SearchAllSubDirectories) }
catch
{
return $_
}
Write-Host "toto"
我不不明白爲什麼它不能按預期工作,我的$GetlocalFolderCheck
應該包含異常,並且不會破壞我的代碼。
感謝您的幫助
非常感謝。初學者錯誤:) –