微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Invoke-AzVMRunCommand 执行脚本

如何解决使用 Invoke-AzVMRunCommand 执行脚本

我目前正在使用以下脚本在 Azure VM 上调用命令。它工作正常,但“脚本”实际上只有一行“代码

$Script = "(Get-WmiObject -class Win32_OperatingSystem).caption"
$scriptPath = "$runID.ps1"

Out-File -FilePath $scriptPath -InputObject $Script
$scriptFile = get-item $scriptPath

$InvokeruncmdOutput_Win = Invoke-AzvmrunCommand -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -CommandId RunPowerShellScript -ScriptPath $scriptPath
$OSCaption = $InvokeruncmdOutput_Win.Value[0].Message

我如何能够使用 Invoke-AzvmrunCommand 从 powershell 执行例如这个 link 脚本。我应该在 $Script 中添加整个脚本,从网络共享调用脚本还是从网络共享复制脚本然后在 vm 中执行?我认为从 netshare 执行/复制并不容易,因为 Runbook(非混合)总是在 NTAUTHORITY\SYstem

下运行

这是另一个我可能会尝试执行的

Stop-Service -Name HealthService

Remove-Item -Path 'C:\Program Files\Microsoft Monitoring Agent\Agent\Health Service State' -Recurse

Start-Service -Name HealthService

Remove-Item HKLM:\SOFTWARE\Microsoft\HybridRunbookWorker -Recurse

解决方法

使用“remoteCommand”选项设置 -ScriptPath。

Set-AzVMCustomScriptExtension,需要一个 VM 可访问的文件才能运行。参考here

ScriptPath 可能在您的计算机本地,您在其中运行 PowerShell,而不是 VM 本身。该命令会将脚本文件的内容注入 VM。为了在没有太多文件的情况下模拟“scriptblock”效果,在运行时将代码放入一个脚本文件中(这样它就会出现在用户运行提示的任何地方),引用它,然后删除它。

# Build a command that will be run inside the VM.

$remoteCommand = Get-Disk | Where-Object partitionstyle -eq 'raw' | Sort-Object Number | Select-Object -first 1 | Initialize-Disk -PartitionStyle GPT  -confirm:$false -PassThru |
New-Partition -DriveLetter 'F' -UseMaximumSize |
Format-Volume -FileSystem NTFS -NewFileSystemLabel "F volume" -Confirm:$false

# Save the command to a local file

Set-Content -Path .\DriveCommand.ps1 -Value $remoteCommand

# Invoke the command on the VM,using the local file

Invoke-AzureRmVMRunCommand -Name $vm.name -ResourceGroupName $vm.ResourceGroupName -CommandId 'RunPowerShellScript' -ScriptPath .\DriveCommand.ps1

# Clean-up the local file

Remove-Item .\DriveCommand.ps1

对于你想在输出流上接收的输出,在脚本内,用“Write-Output”放置。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。