如何成功运行2个不同的脚本Powershell

时间:2018-04-15 16:45:40

标签: function powershell

我有两个不同的代码块。一个针对端点运行,另一个块针对不同的端点运行。如果它们单独运行,它运行正常。但我需要让它们在一个文件中一个接一个地成功运行。有谁可以帮助我吗?

第一块:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

$url = "https://FIRSTENDPOINT.com/Integration-Server/XXXXXXIntegrations?requestJobDescription={""type"":""file"",""credentials"":{""partnerUserID"":""XXXXX"",""partnerUserSecret"":""XXXXXX""},""onReceive"":{""immediateResponse"":[""returnRandomFileName""]},""inputSettings"":{""type"":""combinedReportData"",""filters"":{""startDate"":""2018-01-01""}},""outputSettings"":{""fileExtension"":""pdf"",""includeFullPageReceiptsPdf"":""False"",""fileBasename"":""ExpenseReimbursementReport""}}"

$template = '<#if addHeader == true>
    Employee Name, Amount, Status, Report Date, Employee Email, Report ID<#lt>
</#if>
    <#list reports as report>
    <#setting date_format="MM/dd/yyyy">
    <#setting locale="en_US">
    <#assign total = report.total/100>
    ${report.submitter.fullName},<#t>
    ${total},<#t>   
    ${report.status},<#t>
    ${report.submitted?date("yyyy-MM-dd HH:mm:ss")},<#t>
    ${report.accountEmail},<#t>
    ${report.reportID}<#lt>
</#list>'

$encode = [System.Web.HttpUtility]::UrlEncode($template)

Invoke-RestMethod -ContentType 'application/json' -Method Post -Uri $url'&template='$encode -OutVariable temp

$Data=$temp.split(",")
$var= @{}

$i=0
foreach ($item in $Data)
{$var[$i] = "https://XXXXX.com/Integration-Server/XXXXIntegrations?requestJobDescription={""type"":""download"",""credentials"":{""partnerUserID"":""XXXXX"",""partnerUserSecret"":""XXXXXX""},""fileName"":"+$item+"}"
$output = "C:\files\$item"
Invoke-RestMethod -ContentType 'application/json' -Method Post -Uri $var[$i] -Outfile $output
$i++

第二块:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
$obj = New-Object psobject
$obj | Add-Member -MemberType NoteProperty -Name "username" -Value "XXXXX"
$obj | Add-Member -MemberType NoteProperty -Name "password" -Value "XXXXX"
$body = ConvertTo-Json -InputObject $obj

$login="https://2ndENDPOINT.com/v4/login?fbsite=https://XXXXX.com/"


Invoke-RestMethod -ContentType 'application/json' -Method Post -Body $body -Uri $login -OutVariable AUTHtemp

$filepath="C:\files\"
$data_files = Get-ChildItem $Folder_file_path

$filesss=$data_files | Write-Output

$Data2= $filesss -split "`n"
$var2= @{}

$i2=0
foreach ($item2 in $Data2)
{


$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept", 'application/pdf')

$fileName="C:\files\$item2"
$fileContent = get-content -Raw $fileName
$fileContentBytes = [System.Text.Encoding]::Default.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)


$data = ConvertTo-Json @{

encrypted="false";
allowSaveBinaryData="true";
binaryData="$fileContentEncoded"
divider="Expense Report";
extension="pdf";
name="$fileContentEncoded";
relProjectId="31";
fileID="597"
}

$var2[$i2]="https://XXXXXX.com/v4/documents/597?guid=$AUTHtemp&fbsite=https://XXXXXX.com/"

Invoke-RestMethod -headers $headers -ContentType 'application/json' -Method PUT -body $data -Uri $var2[$i2]}

$i2++

修改

当我尝试在同一个文件中运行它们时,无论是作为一个块还是作为函数,它都会引发大量错误。我不得不在第12次错误后停止它,因为它每次都只是创建空文件并抛出错误:

get-content : Cannot find path 'C:\files\Box Sync' because it does not exist.
At C:\Users\USER\Documents\ExpenseReimbursement_Powershell\Expense_GetReports.ps1:65 char:16
+ $fileContent = get-content -Raw $fileName
+                ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\files\Box Sync:String) [Get-Content], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Exception calling "GetBytes" with "1" argument(s): "Array cannot be null.
Parameter name: chars"
At C:\Users\USER\Documents\ExpenseReimbursement_Powershell\Expense_GetReports.ps1:66 char:1
+ $fileContentBytes = [System.Text.Encoding]::Default.GetBytes($fileCon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

Exception calling "ToBase64String" with "1" argument(s): "Value cannot be null.
Parameter name: inArray"
At C:\Users\USERNAME\Documents\ExpenseReimbursement_Powershell\Expense_GetReports.ps1:67 char:1
+ $fileContentEncoded = [System.Convert]::ToBase64String($fileContentBy ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

1 个答案:

答案 0 :(得分:2)

最直接的方法是将第一个块之后的整个第二个代码块放在同一个文件中。

此时程序会自然地从第一个流到第二个。

但是由于每个块似乎代表一个特定的操作,这可能是一个很好的机会将每个块放在一个函数中来封装它。

这也允许您将代码转换为一种“模板”,因为您可以传入可能作为参数更改的值,然后您可以获得一组可重用的操作。我现在还不会讨论这个问题,但需要考虑一下。

我不完全确定你的第一个块应该做什么(作为一个高级操作),但我会猜测并将其描述为“后整合结果”,所以我将调用此函数{ {1}}(这遵循PowerShell Register-IntegrationResult命名约定,使用已批准的动词和单数名词,但您可以将该函数命名为您想要的任何内容):

Verb-Noun

与第二块类似,我不知道它在做什么,但我猜它正在上传某种报告,所以我称之为function Register-IntegrationResult { [Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls" $url = "https://FIRSTENDPOINT.com/Integration-Server/XXXXXXIntegrations?requestJobDescription={""type"":""file"",""credentials"":{""partnerUserID"":""XXXXX"",""partnerUserSecret"":""XXXXXX""},""onReceive"":{""immediateResponse"":[""returnRandomFileName""]},""inputSettings"":{""type"":""combinedReportData"",""filters"":{""startDate"":""2018-01-01""}},""outputSettings"":{""fileExtension"":""pdf"",""includeFullPageReceiptsPdf"":""False"",""fileBasename"":""ExpenseReimbursementReport""}}" $template = '<#if addHeader == true> Employee Name, Amount, Status, Report Date, Employee Email, Report ID<#lt> </#if> <#list reports as report> <#setting date_format="MM/dd/yyyy"> <#setting locale="en_US"> <#assign total = report.total/100> ${report.submitter.fullName},<#t> ${total},<#t> ${report.status},<#t> ${report.submitted?date("yyyy-MM-dd HH:mm:ss")},<#t> ${report.accountEmail},<#t> ${report.reportID}<#lt> </#list>' $encode = [System.Web.HttpUtility]::UrlEncode($template) Invoke-RestMethod -ContentType 'application/json' -Method Post -Uri $url'&template='$encode -OutVariable temp $Data=$temp.split(",") $var= @{} $i=0 foreach ($item in $Data) { $var[$i] = "https://XXXXX.com/Integration-Server/XXXXIntegrations?requestJobDescription={""type"":""download"",""credentials"":{""partnerUserID"":""XXXXX"",""partnerUserSecret"":""XXXXXX""},""fileName"":"+$item+"}" $output = "C:\files\$item" Invoke-RestMethod -ContentType 'application/json' -Method Post -Uri $var[$i] -Outfile $output $i++ } }

Send-ImportantReport

那么这有什么意义呢?现在当你想要一个接一个地调用时,你的代码看起来像这样:

function Send-ImportantReport {
    [Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
    $obj = New-Object psobject
    $obj | Add-Member -MemberType NoteProperty -Name "username" -Value "XXXXX"
    $obj | Add-Member -MemberType NoteProperty -Name "password" -Value "XXXXX"
    $body = ConvertTo-Json -InputObject $obj

    $login="https://2ndENDPOINT.com/v4/login?fbsite=https://XXXXX.com/"


    Invoke-RestMethod -ContentType 'application/json' -Method Post -Body $body -Uri $login -OutVariable AUTHtemp

    $filepath="C:\files\"
    $data_files = Get-ChildItem $Folder_file_path

    $filesss=$data_files | Write-Output

    $Data2= $filesss -split "`n"
    $var2= @{}

    $i2=0
    foreach ($item2 in $Data2)
    {


        $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $headers.Add("Accept", 'application/pdf')

        $fileName="C:\files\$item2"
        $fileContent = get-content -Raw $fileName
        $fileContentBytes = [System.Text.Encoding]::Default.GetBytes($fileContent)
        $fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)


        $data = ConvertTo-Json @{
            encrypted="false";
            allowSaveBinaryData="true";
            binaryData="$fileContentEncoded"
            divider="Expense Report";
            extension="pdf";
            name="$fileContentEncoded";
            relProjectId="31";
            fileID="597"
        }
    }
}

如果您需要多次执行此操作,只需按名称拨打电话。

作为未来的更改,您可能希望添加参数,这样可以传递可以更改的部分,例如凭据,URL或本地文件路径。然后您的调用可能如下所示:

Register-IntegrationResult
Send-ImportantReport