Ho khutlisetsa boleng ho tloha ho powershell invoke-command ho SQL Server agent

Ha ke theha mokhoa oa ka oa ho laola li-backups ho li-server tse ngata tsa MS-SQL, ke ile ka qeta nako e ngata ke ithuta mochine oa ho fetisa boleng ho Powershell nakong ea mehala e hole, kahoo ke ingolla khopotso haeba e ka ba molemo. ho motho emong.

Kahoo, ha re qaleng ka mongolo o bonolo 'me re o tsamaise sebakeng sa heno:

$exitcode = $args[0]
Write-Host 'Out to host.'
Write-Output 'Out to output.'
Write-Host ('ExitCode: ' + $exitcode)
Write-Output $exitcode
$host.SetShouldExit($exitcode)

Ho tsamaisa lingoloa, ke tla sebelisa faele e latelang ea CMD, nke ke ka e kenyelletsa nako le nako:

@Echo OFF
PowerShell .TestOutput1.ps1 1
ECHO ERRORLEVEL=%ERRORLEVEL%

Ka skrineng re tla bona tse latelang:

Out to host.
Out to output.
ExitCode: 1
1
ERRORLEVEL=1


Joale ha re tsamaise sengoloa se tšoanang ka WSMAN (hole):

Invoke-Command -ComputerName . -ScriptBlock { &'D:sqlagentTestOutput1.ps1' $args[0] } -ArgumentList $args[0]

Mme sephetho ke sena:

Out to host.
Out to output.
ExitCode: 2
2
ERRORLEVEL=0

E kholo, Errorlevel e nyametse kae-kae, empa re hloka ho fumana boleng ho tsoa ho script! Ha re leke kaho e latelang:

$res=Invoke-Command -ComputerName . -ScriptBlock { &'D:sqlagentTestOutput1.ps1' $args[0] } -ArgumentList $args[0]

Sena se thahasellisa le ho feta. Molaetsa o ho Output o nyametse kae-kae:

Out to host.
ExitCode: 2
ERRORLEVEL=0

Joale, joalo ka tšitiso ea mantsoe, ke tla hlokomela hore haeba ka har'a ts'ebetso ea Powershell u ngola Write-Output kapa polelo feela ntle le ho e abela mofuta ofe kapa ofe ('me sena se bolela ka mokhoa o hlakileng tlhahiso ea Output channel), leha o sebetsa sebakeng sa heno, ha ho letho le tla hlahisoa skrineng! Sena ke sephetho sa meralo ea lipeipi tsa powershell - ts'ebetso e 'ngoe le e' ngoe e na le phaephe ea eona ea Output, sehlopha se etselitsoe eona, 'me ntho e ngoe le e ngoe e kenang ho eona e nkuoa e le sephetho sa ts'ebetso ea ts'ebetso. pipeline e le ntho ea ho qetela le ho fetisetsa taolo mosebetsing oa ho letsetsa. Ho etsa mohlala, ha re tsamaise sengoloa se latelang sebakeng sa heno:

Function Write-Log {
  Param( [Parameter(Mandatory=$false, ValueFromPipeline=$true)] [String[]] $OutString = "`r`n" )
  Write-Output ("Function: "+$OutString)
  Return "ReturnValue"
}
Write-Output ("Main: "+"ParameterValue")
$res = Write-Log "ParameterValue"
$res.GetType()
$res.Length
$res | Foreach-Object { Write-Host ("Main: "+$_) }

Mme sephetho ke sena:

Main: ParameterValue

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
2
Main: Function: ParameterValue
Main: ReturnValue

Mosebetsi oa mantlha (script body) le ona o na le phaephe ea ona ea Output, 'me haeba re tsamaisa sengoloa sa pele ho tsoa ho CMD, re fetisetsa tlhahiso ho faele,

PowerShell .TestOutput1.ps1 1 > TestOutput1.txt

joale re tla bona skrineng

ERRORLEVEL=1

le faeleng

Out to host.
Out to output.
ExitCode: 1
1

haeba re etsa mohala o ts'oanang ho tsoa ho powershell

PS D:sqlagent> .TestOutput1.ps1 1 > TestOutput1.txt

joale e tla ba skrineng

Out to host.
ExitCode: 1

le faeleng

Out to output.
1

Sena se etsahala hobane CMD e qala powershell, eo, ha ho se na litaelo tse ling, e kopanya likhoele tse peli (Host and Output) ebe e li fa CMD, e romellang ntho e 'ngoe le e' ngoe eo e e fumaneng faeleng, 'me tabeng ea ho matha ho tloha powershell, likhoele tsena tse peli li teng ka thoko, 'me li-redirect tsa letšoao li ama Output feela.

Ha re khutlela sehloohong se seholo, a re hopoleng hore .NET ntho ea mohlala ka hare ho powershell e teng ka ho feletseng ka har'a k'homphieutha e le 'ngoe (OS e le' ngoe), ha ho sebetsa khoutu ka thōko ka WSMAN, ho fetisoa ha lintho ho etsahala ka XML serialization, e leng se tlisang thahasello e eketsehileng. ho lipatlisiso tsa rona. Ha re ntšetseng pele liteko tsa rona ka ho sebelisa khoutu e latelang:

$res=Invoke-Command -ComputerName . -ScriptBlock { &'D:sqlagentTestOutput1.ps1' $args[0] } -ArgumentList $args[0]
$res.GetType()
$host.SetShouldExit($res)

'Me sena ke seo re nang le sona skrineng:

Out to host.

ExitCode: 3

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
Не удается преобразовать аргумент "exitCode", со значением: "System.Object[]", для "SetShouldExit" в тип "System.Int32": "Не удается преобразовать значение "System.Object[]" типа "System.Object[]" в тип "System
.Int32"."
D:sqlagentTestOutput3.ps1:3 знак:1
+ $host.SetShouldExit($res)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

ERRORLEVEL=0

Sephetho se setle! Ho bolela hore ha o letsetsa Invoke-Command, karohano ea lipeipi ka likhoele tse peli (Host and Output) e bolokiloe, e re fang tšepo ea katleho. Ha re leke ho siea boleng bo le bong feela ho Output stream, eo re tla fetola mongolo oa pele oo re o tsamaisang re le hole:

$exitcode = $args[0]
Write-Host 'Out to host.'
#Write-Output 'Out to output.'
Write-Host ('ExitCode: ' + $exitcode)
Write-Output $exitcode
$host.SetShouldExit($exitcode)

Ha re e tsamaise tjena:

$res=Invoke-Command -ComputerName . -ScriptBlock { &'D:sqlagentTestOutput1.ps1' $args[0] } -ArgumentList $args[0]
$host.SetShouldExit($res)

le ... YES, e shebahala joaloka tlhōlo!

Out to host.
ExitCode: 4

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType


ERRORLEVEL=4

A re lekeng ho fumana hore na ho etsahetse’ng. Re ile ra letsetsa powershell sebakeng sa heno, eo le eona e ileng ea bitsa powershell komporong e hole mme ra etsa mongolo oa rona moo. Melapo e 'meli (Host and Output) e tsoang mochining o hole e ile ea hlophisoa mme ea khutlisetsoa morao, athe Output stream, e nang le boleng bo le bong ba dijithale ho eona, e ile ea fetoloa mofuta oa Int32 mme ka hona e fetisetsoa lehlakoreng le amohelang, mme lehlakore le amohelang le ile la e sebelisa. joalo ka khoutu ea ho tsoa ea motho ea letsetsang powershell.

E le cheke ea ho qetela, ha re theheng mosebetsi oa mohato o le mong ho seva sa SQL ka mofuta oa "Operating System (cmdexec)" ka mongolo o latelang:

PowerShell -NonInteractive -NoProfile "$res=Invoke-Command -ComputerName BACKUPSERVER -ConfigurationName SQLAgent -ScriptBlock {&'D:sqlagentTestOutput1.ps1' 6}; $host.SetShouldExit($res)"

HOORAY! Mosebetsi o phethiloe ka phoso, mongolo ho log:

Выполняется от имени пользователя: DOMAINagentuser. Out to host. ExitCode: 6.  Код завершения процесса 6.  Шаг завершился с ошибкой.

Qeto:

  • Qoba ho sebelisa Write-Output le ho hlakisa lipolelo ntle le mosebetsi. Hlokomela hore ho tsamaisa khoutu ena sebakeng se seng ho ka hlahisa liphetho tse sa lebelloang.
  • Lingoliloeng tse sa reretsoeng ho qala ka letsoho, empa bakeng sa ts'ebeliso mecheng ea hau ea boiketsetso, haholo-holo bakeng sa mehala e hole ka WINRM, etsa liphoso tsa letsoho ka Try/Catch, 'me u netefatse hore, nts'etsopeleng efe kapa efe ea liketsahalo, sengoloa sena se romella boleng ba mofuta o le mong oa khale. . Haeba u batla ho fumana Errorlevel ea khale, boleng bona e tlameha ho ba linomoro.

Source: www.habr.com

Eketsa ka tlhaloso