gpt4 book ai didi

powershell - 检查命令是否运行成功

转载 作者:行者123 更新时间:2023-12-01 18:35:24 25 4
gpt4 key购买 nike

我尝试将以下内容包含在 if 语句中,以便在成功时可以执行另一个命令:

Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" | Foreach-Object {
$Localdrives += $_.Path

但我不知道该怎么做。我什至尝试创建一个函数,但我不知道如何检查该函数是否已成功完成。

最佳答案

尝试使用 $? 自动变量:

$share = Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'"

if($?)
{
"command succeeded"
$share | Foreach-Object {...}
}
else
{
"command failed"
}

来自about_Automatic_Variables :

$?
Contains the execution status of the last command.
It contains True if the last command succeeded and False if it failed.
...

$LastExitCode
Contains the exit code of the last native program or PowerShell script that ran.

关于powershell - 检查命令是否运行成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com