首页 > 解决方案 > 如何通过从具有管理员权限的批处理文件中传递路径参数来调用 powershellscript 文件?

问题描述

我知道这在互联网上有很多答案。我尝试了许多示例代码,但对我不起作用。我的要求:我有一个 powershell 文件 CreateLink.ps1,它使用给定的链接名称($link)为目标文件夹($destination)中的源文件夹($source)创建一个链接。所有三个值都作为参数传递给该文件。如果我使用 Powershell CLI 执行这些

C:\codedeploy\UAT\CreateLink.ps1 -source C:\Deployments\UAT\ -destination C:\codedeploy\UAT\release -link publish

在源路径中创建目标路径 C:\codedeploy\UAT\release 的软链接名称发布工作正常。下面是 CreateLink.ps1 代码:

param([parameter(mandatory=$true)]
   $source,
   $destination,
   $link)
# Write-Host $source
# Write-Host $destination

if ($PSHOME -like "*SysWOW64*")
    {
        Write-Warning "Restarting this script under 64-bit Windows PowerShell."

        # Restart this script under 64-bit Windows PowerShell.
        #   (\SysNative\ redirects to \System32\ for 64-bit mode)

        & (Join-Path ($PSHOME -replace "SysWOW64", "SysNative") powershell.exe) -File `
        (Join-Path $PSScriptRoot $MyInvocation.MyCommand) @args

        # Exit 32-bit script.

        Exit $LastExitCode
    }
    
# Release Root path
$release_root="$source"

# Deployment Root path
$deployment_root="$destination"

$symlink="$link"
# Make a Symlink path
$pathLink="$release_root\$symlink"

# Delete Symlink if exists and create anew
if((Test-Path $pathLink) -ne 0)
{
    Write-Output "Delete release Link: $pathLink<--"  
    # Powershell issue w/ Symlinks
    # https://github.com/PowerShell/PowerShell/issues/621
    # Fix: https://kristofmattei.be/2012/12/15/powershell-remove-item-and-symbolic-links/
    # rm -r $pathLink -Force 
    $RMDIR = "/c rmdir $pathLink"
    Start-Process cmd.exe  -ArgumentList $RMDIR -Wait
}
 
$MKLINK = "/c mklink /D $pathLink $deployment_root"
Start-Process cmd.exe  -ArgumentList $MKLINK -Wait

现在我需要在 jenkins 作业中的批处理文件 after-deploy.bat 中使用参数调用这个 powershell 脚本文件。我尝试了以下代码:

Powershell.exe -executionpolicy remotesigned -File C:\codedeploy\UAT\CreateLink.ps1 -source C:\Deployments\UAT\ -destination C:\codedeploy\UAT\release -link publish

powershell -Command "&{ Start-Process powershell -ArgumentList '-File C:\codedeploy\UAT\CreateLink.ps1' -source C:\Deployments\UAT\ -destination C:\codedeploy\UAT\release -link publish  -Verb RunAs}"

其他一些命令也对我不起作用。任何有关如何使用批处理文件中的参数运行此命令的帮助将不胜感激。如果可能,请提供代码片段。

提前致谢。

标签: powershellbatch-filejenkinspowershell-3.0powershell-4.0

解决方案


推荐阅读