I'm writing a PowerShell script that will execute a command on a remote server. I'm using a single variable in the script as a parameter to that command.
param(
[Parameter(Mandatory=$true)][string]$strUser
)
$strDomain = "company.com\\"
$strFQusername = $strDomain + $strUser
$strFQusername
$strFQusername
$strFQusername
Invoke-Command -computername VMwareView.company.com -scriptblock {. $env:userprofile\document\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ; Get-RemoteSession -username $strFQusername } -credential company.com\administrator
$strFQusername
$strFQusername
$strFQusername
When I execute this script, the $strFQusername variable appears to be replaced by a wildcard. The Get-RemoteSession cmdlet is executed correctly, however it lists the sessions for all users, not just the user specified by the $strFQusername variable. This would be the equivalent of me entering Get-RemoteSession -username * .
If I hard code the username in the script, I get the expected output. That is, I see the session for only the username I hard coded into the script.
I've tried using single and double backslashes in the $strDomain variable, but got the same results. The 3 lines of $strFQusername you see before and after the Invoke-Command line are there for debugging. They print out exactly the string I would expect to see stored in $strFQusername .
What am I missing?
Use the modifier $using
if you have ps3+ or the paramétrer -argumentlist
if ps2
Ps3+ :
..Get-RemoteSession -username $using:strFQusername
Ps2
...{Param ($user)....Get-RemoteSession -username $user} -arg $strFQusername
The scriptblock doesn't know variables outside of it, so you need to pass them into the scriptblock via the -ArgumentList
parameter:
Invoke-Command -computername VMwareView.company.com -scriptblock {
. $env:userprofile\document\WindowsPowerShell\Microsoft.PowerShell_profile.ps1;
Get-RemoteSession -username
} -credential company.com\administrator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.