【问题标题】:Passing PowerShell variables to filepath将 PowerShell 变量传递给文件路径
【发布时间】:2020-12-28 00:35:44
【问题描述】:

对 Powershell 完全陌生,但对编程并不陌生。无论如何,我试图编辑这个已经创建的脚本,它几乎可以工作了。我不明白如何让 Powershell 将用户分配的变量传递到我的调用命令 (\MICROS\Res\pos\scripts\$ScriptName) 的文件路径中。您能提供的任何帮助都将得到极大的应用。

#Gather user input for name of script
$ScriptName=Read-Host "Enter the name of the script that you want to run [Examples: HH_Off.bat]"

#Loop through store array
foreach ($CurrentStore in $store) { #START LOOP
#How to call current store Name: $CurrentStore.Name
#How to call current store IP: $CurrentStore.IP
#How to call current store City: $CurrentStore.City
if ($RunListArray -contains $CurrentStore.ID){ #If the current store is in the input list
Write-Host " *** "$CurrentStore.City"("$CurrentStore.Name")"
$NetworkDrivePath = "\\" + $CurrentStore.IP + "\D$"

#Create Network Drives
New-PSDrive -Name $CurrentStore.Name -PSProvider FileSystem -Root $NetworkDrivePath -credential $mycred

#Check if site is responding
If (Test-Path -Path $NetworkDrivePath)
{
Write-Host " *** *** NETWORK DRIVE FOUND!!! PROCEEDING..."
Invoke-Command {powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$ScriptName} -computername $CurrentStore.IP -credential $mycred

#REMOVE PS DRIVE
Remove-PSDrive $CurrentStore.Name
}
Else {
Write-Host " *** *** NETWORK DRIVE NOT FOUND, SENDING ERROR EMAIL"
$Subject = "*Testing*Powershell Error Send Files Script" + $CurrentStore.Name + " (" + $CurrentStore.City + ")"
$Body = "Network path " + $NetworkDrivePath + " is not accessible."
SendErrorEmail $Subject $Body
}
} #END LOOP
}

【问题讨论】:

    标签: powershell variables


    【解决方案1】:

    该变量是在本地(调用)会话中定义的,而不是在远程(Invoke-Command)会话中定义的。它被称为范围。您可以像这样使用变量修饰符$using: 进入调用范围

    Invoke-Command {powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$using:ScriptName} -computername $CurrentStore.IP -credential $mycred
    

    或者使用-ArgumentList作为命名或未命名参数

    #named parameter
    Invoke-Command {Param($script)powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$script} -computername $CurrentStore.IP -credential $mycred -ArgumentList $ScriptName
    
    #unnamed parameter
    Invoke-Command {powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$args[0]} -computername $CurrentStore.IP -credential $mycred -ArgumentList $ScriptName
    

    格式化并使用喷溅以提高可读性

    $sb = {
        Param($script)
        powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$script
    }
    
    $params = @{
        ScriptBlock  = $sb
        ComputerName = $CurrentStore.IP
        Credential   = $mycred
        ArgumentList = $ScriptName
    }
    
    Invoke-Command @params
    

    此外,您可能也应该避免对 powershell.exe 的额外调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多