将 PowerShell 变量传递给文件路径

时间:2020-12-28 00:35:44

标签: powershell variables

对 Powershell 完全陌生,但对编程并不陌生。无论如何,我正在尝试编辑这个已经创建的脚本,它几乎可以正常工作。我不明白如何让 Powershell 将用户分配的变量传递到我的 invoke-command (\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
}

1 个答案:

答案 0 :(得分:0)

该变量是在本地(调用)会话中定义的,而不是在远程(调用命令)会话中定义的。它被称为范围。您可以像这样使用变量修饰符 $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。