Max*_*tin 5 powershell azure azure-powershell azure-devops azureshell
我在 Azure PowerShell 中创建了一个脚本。
如果我使用“echo”命令,它会将输出显示到控制台。
但是,如果我使用 Write-Output 和 Write-Error,我看不到输出。
我已将脚本“change-to-static.ps1”上传到存储帐户。然后我使用顶部栏上的按钮打开“Cloud Shell”。然后我在 PowerShell 控制台中输入“./change-ip-to-static.ps1”。
因此,除非我用“echo”或“print”替换“Write-Output”和“Write-Error”,否则脚本不会产生任何输出。
请帮我。我应该做什么才能看到输出?
脚本如下。
How to output Something in PowerShell有一个类似的问题。我已阅读它,但没有关于如何实现我的目标的具体示例,即如何修改我的脚本以查看输出。就我而言,即使我重定向到文本文件,它也不会输出。然而,在我的例子中,“echo”和“print”等命令可以工作,但上面的示例中没有涵盖它们。请参阅下面的脚本。
$IPs = Get-AzPublicIpAddress;
$Static = "Static";
foreach ($PublicIP in $IPs) {
$Method = $PublicIP.PublicIpAllocationMethod;
$Name = $PublicIP.Name;
if ($Method -eq $Static) {
$message = "The method of " + $Name + " is already " + $Static;
Write-Progress -Activity $message;
}
else {
Write-Progress -Activity "Changing the method of "+$Name+" from "+$Method+" to "+$Static+"...";
$PublicIP.PublicIpAllocationMethod = $Static;
Set-AzPublicIpAddress -PublicIpAddress $PublicIP;
Write-Progress -Activity "Querying the method of "+$Name+"...";
$ModifiedAddress = Get-AzPublicIpAddress -Name $Name -ResourceGroupName $PublicIP.ResourceGroupName -Location $PublicIP.Location
$NewMethod = $ModifiedAddress.PublicIpAllocationMethod;
if ($NewMethod -eq $Static) {
Write-Output "The method for "+$Name+" has successfully changed to "+$Static;
}
else {
Write-Error -Message "Cannot change the method for "+$Name+" to "+$Static+", it is still "+$NewMethod+"!!!";
}
}
}
Run Code Online (Sandbox Code Playgroud)
PS我已经根据建议更新了脚本(使用此URL),但仍然没有输出。只有“echo”或“print”给出输出。PPSWrite-Progress甚至不会在状态行中显示临时消息,在此期间Set-AzPublicIpAddress需要几秒钟才能完成,或者如果我添加 cmdlet Start-Sleep。它仅在 期间设置Get-AzPublicIpAddress。
在阅读了您对我的答案的最后一次编辑后,我相信您在使用命令行开关和脚本逻辑方面有些困惑Write-*,因此我提供了带有上下文的更详细的答案。
echo在 Powershell Azure Cloud Shell 中是 的别名Write-Output,不带参数执行清楚地显示了这一点(此处的echo文档)。
PS /home/mikelangelo> echo
cmdlet Write-Output at command pipeline position 1
Supply values for the following parameters:
InputObject:
Run Code Online (Sandbox Code Playgroud)
而且:unixecho还可以在Powershell Azure Cloud Shell中运行。
PS /home/mikelangelo> which echo
/usr/bin/echo
PS /home/mikelangelo> /usr/bin/echo ciao mondo
ciao mondo
Run Code Online (Sandbox Code Playgroud)
print另一方面,它不是 Powershell 别名,因此 unix 对应项是在使用关键字时始终执行的别名print(目前是一个符号链接run-mailcap- 但我不清楚它如何在您的用例中发挥作用。)
PS /home/mikelangelo> which print
/usr/bin/print
Run Code Online (Sandbox Code Playgroud)
因此,基本上,echo 和 Write-Output都会起作用,因为它们调用相同的命令行开关,除非您/usr/bin/echo直接执行,从而混合技术并有效地损害可移植性。
回到问题:
Write-Output按预期工作。逻辑是错误的:你使用=作为比较运算符,但你需要使用-eq。
Write-Progress需要以不同方式使用,请将其替换为Write-Host或Write-Output。请参阅文档以获取解释。
请注意,Write-Output沿着管道发送一个对象,该对象最终可以表示为控制台输出。
Write-Progress另一方面Write-Host,不生成输出 - 后者将一个对象发送到主机进行显示,因此Write-Host是在控制台中显示某些内容的推荐方法。有关和 Powershell 管道的更多详细信息,请参阅此问题。Write-HostWrite-Output
| 归档时间: |
|
| 查看次数: |
4605 次 |
| 最近记录: |