this is probably an easy answer for you experts but not sure the best command to use. I want to execute the following command from within powershell :
stccmd -rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb nsccahs_dev_cb -cmd "status bobRRC_ADT_OUT_FMT"
and return the result.
The code i have so far is :
$sCmd = #'
"stccmd -rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb
nsccahs_dev_cb -cmd '\"status bobRRC_ADT_OUT_FMT\"'"
'#
$Result = Invoke-Command $sCmd | Out-String
The error i am getting is :
Invoke-Command : Parameter set cannot be resolved using the specified named par
ameters.
At E:\Andrew\MonitoreGate.ps1:20 char:25
+ $Result = Invoke-Command <<<< $sCmd | Out-String
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], Parameter
BindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Comma
nds.InvokeCommandCommand
If i use Invoke-Expression, instead i get the following :
Invoke-Expression : Unexpected token 'status' in expression or statement.
At E:\Andrew\MonitoreGate.ps1:20 char:28
+ $Result = Invoke-Expression <<<< $sCmd | Out-String
+ CategoryInfo : ParserError: (status:String) [Invoke-Expression]
, ParseException
+ FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Commands.In
vokeExpressionCommand
Should i be using Invoke-Command or Invoke-Expression or some other way? Is the $sCmd structure correct in regards to quotes?
The program is to run on same machine (not remotely).
Any help greatly appreciated,
Andrew
neither, instead use:
Start-Process -FilePath 'path_to_stccmd.exe' -ArgumentList "-rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb nsccahs_dev_cb -cmd 'status bobRRC_ADT_OUT_FMT'" -nonewwindow
if you dont see the output using the above...try this:
$exepath = 'path_to_stccmd.exe'
&$exepath arguments
Related
When I run the following command in my script I expect packet_dump.pcap to get generated after I stop the script but nothing gets generated.
Start-Job -Name $tsharkJobName -ScriptBlock { & $tsharkPath --interface $interfaceNo -w "packet_dump.pcap" } | Out-Null
When I run the line below:
Receive-Job $tsharkJobName -Force
This is the error message that I get (where $interfaceNo is 5 which is the ID for Wi-Fi):
Capturing on 'Wi-Fi'
+ CategoryInfo : NotSpecified: (Capturing on 'Wi-Fi':String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : localhost
I have this at the end of the script as well:
finally {
Stop-Job $tsharkJobName
Remove-Job $tsharkJobName -Force
}
$args = "--interface " + $interfaceNo + " -w packet_dump.pcap"
Start-Process $tsharkPath -ArgumentList $args -NoNewWindow
and
finally {
Stop-Process -Name "tshark"
}
Solves this.
I'm trying to execute this script using Splatting for the remote server (through PowerShell ISE).
However, it is always stuck and failed.
I've followed the suggestion as in https://www.ibm.com/support/knowledgecenter/en/SSKMKU/com.ibm.wincollect.doc/t_ug_wincollect_cli_install.html
Script:
$Args = #{
'EXE'='\\PRDFS01-VM\DSL\wincollect-7.3.0-24.x64.exe'
'INSTALLDIR'='C:\Program Files\IBM\WinCollect\'
'LOG_SOURCE_AUTO_CREATION_ENABLED'='True'
'LOG_SOURCE_AUTO_CREATION_PARAMETERS'=""
'Component1.AgentDevice'='DeviceWindowsLog'
'Component1.Action'='create'
'Component1.LogSourceName'="$env:COMPUTERNAME"
'Component1.LogSourceIdentifier'="$env:COMPUTERNAME"
'Component1.Dest.Name'='IBMQradar'
'Component1.Dest.Hostname'='192.168.111.111'
'Component1.Dest.Port'='514'
'Component1.Dest.Protocol'='TCP'
'Component1.Log.Security'='true'
'Component1.Log.System'='true'
'Component1.Log.Application'='true'
'Component1.Log.DNS+Server'='true'
'Component1.Log.File+Replication+Service'='true'
'Component1.Log.Directory+Service'='true'
'Component1.RemoteMachinePollInterval'='3000'
'Component1.EventRateTuningProfile'='Default+(Endpoint)'
'Component1.MinLogsToProcessPerPass'='100'
'Component1.MaxLogsToProcessPerPass'='150'
}
$process = Start-Process -ArgumentList "/s" "/v" "/qn" #Args -Wait -PassThru
$process.ExitCode
Error:
At line:9 char:15
+ Component1.Action=create
+ ~
Missing '=' operator after key in hash literal.
At line:29 char:18
+ $process.ExitCode
+ ~
Missing '=' operator after key in hash literal.
At line:29 char:18
+ $process.ExitCode
+ ~
The hash literal was incomplete.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingEqualsInHashLiteral
OK, after updating it as above, now the error is different:
Start-Process : A positional parameter cannot be found that accepts argument '/qn'.
At line:25 char:12
+ $process = Start-Process -ArgumentList "/s" "/v" "/qn" #Args -Wait -P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
Hashtable keys cannot contain dots unless you quote them.
This doesn't work.
$Args = #{
EXE='\\PRDFS01-VM\DSL\wincollect-7.3.0-24.x64.exe /s /v"/qn'
Component1.Action=create
}
This does (note that create also requires quotes)
$Args = #{
EXE='\\PRDFS01-VM\DSL\wincollect-7.3.0-24.x64.exe /s /v"/qn'
'Component1.Action'='create'
}
ISE will actually even give you syntax errors about this, so I'm not quite sure how that went unnoticed.
I tried different ways to escape the space in "Program Files" but this is not working. I receive the following error in Jenkins after this part is executed:
powershell.exe : FileStream was asked to open a device that was not a file. For support for devices like 'com1:' or 'lpt1:', call At
C:\web\JenkinsMaster\workspace\XXX#tmp\durable-d3011838\powershellWrapper.ps1:5
char:3
+ & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (FileStream was ... 'lpt1:', call :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError CreateFile, then use the FileStream constructors that take an OS handle as an IntPtr.
CategoryInfo : OpenError: (:) [Out-File], NotSupportedException
FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
PSComputerName : XXXXX
powershell script: '''
$pass = ConvertTo-SecureString -AsPlainText "XXXX" -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "XXXX",$pass
$sessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ComputerName XXXXXXXX -UseSSL -Credential $cred -SessionOption $sessionOption
Copy-Item $env:WORKSPACE\\* -Destination "C:\\data\\install\\" -Filter *TEST* -Recurse -Force -Verbose -ToSession $session
$filename = $env:JOB_NAME + "_" + $env:BUILD_DISPLAY_NAME + "_wwwroot.7z"
Invoke-Command -Session $session -ScriptBlock {cmd /c "C:\\Program Files\\7-Zip\\7z.exe\\" x C:\\Data\\Install\\$filename -oC:\\data\\install\\test -aoa >NUL}
Remove-PSSession $session
Exit-PSSession
'''
If I change the Invoke-Command to the following, the Program Files directory seems to be resolved correctly, but then the variable $filename is not resolved anymore.
Invoke-Command -Session $session -ScriptBlock {cmd /c \'"C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\$filename -oC:\\data\\install\\test -aoa >NUL'}
powershell.exe : NotSpecified: (:String) [], RemoteException At
C:\web\Jenkins\workspace\XXX#tmp\durable-53dbead2\powershellWrapper.ps1:5
char:3
+ & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (NotSpecified: (...RemoteException:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
CategoryInfo : NotSpecified: (:String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
PSComputerName : XXXXX
ERROR: The system cannot find the file specified.
C:\Data\Install\$filename
System ERROR:
The system cannot find the file specified.
Hopefully you can assist me in this case! The rest of the commands is working fine.
Thanks!
The 7z.exe path in your first command has an extraneous trailing \, which causes problems:
cmd /c "C:\\Program Files\\7-Zip\\7z.exe\\" # <- trailing \\ shouldn't be there
In your 2nd command, you're using single quotes around the command passed to cmd /c ('...'), but the contents of '...' strings in PowerShell are treated as literals, which explains why $fileName was not expanded (interpolated);
only double-quoted ("...") strings and, within limits, unquoted command arguments are expanded in PowerShell; e.g., compare the output from Write-Output '$HOME' to the output from Write-Output "$HOME" / Write-Output $HOME.
As iRon mentions, there's no need to involve cmd at all - PowerShell is perfectly capable of executing command-line programs directly, so this should work:
Invoke-Command -Session $session -ScriptBlock { & "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\$using:filename -oC:\\data\\install\\test -aoa >$null }
Due to invoking 7z.exe directly, now there's no outer quoting needed anymore, and $fileName should be expanded.
Note, however, that $fileName was replaced with $using:fileName, which is necessary in order for the target session to know about the local $fileName variable - see Get-Help about_Remote_Variables.
Since the 7z.exe file path is quoted (of necessity, due to containing spaces), you must use &, the call operator, to invoke it.
Since the > redirection is now performed by PowerShell itself, the cmd-style >NUL output suppression was replaced with its PowerShell analog, >$null.
I wonder if it necessarily at all to invoke a CMD shell for this.
I guess it would be simpler to directly invoke the 7z.exe with its parameters.
Nevertheless, you can build you own script block like this:
[ScriptBlock]::Create('cmd /c "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\' + $filename + ' -oC:\\data\\install\\test -aoa >NUL')
I am trying to individually monitor memory usage of a process (w3wp.exe) that has multiple instances of itself by filtering out a string found in the process' CommandLine property.
It works when I run this script locally:
$proc = (WmiObject Win32_Process -Filter "Name = 'w3wp.exe'" | Where-Object {$_.CommandLine -like "*SomeTextFromCl*"})
$id = $proc.ProcessId
$ws = [math]::round((Get-Process -Id $id).WS/1MB)
Write-Host $ws
However, when I try to run it remotely through Invoke-Command, I get an error telling that the Id property's value is null:
Cannot bind argument to parameter 'Id' because it is null.
+ CategoryInfo : InvalidData: (:) [Get-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetProcessCommand
+ PSComputerName : RemoteServerName
My Invoke-Command syntax is:
Invoke-Command -ComputerName RemoteServerName -FilePath script.ps1 -Credential $mycredential
I'm sure it's simple but I'm back to PS after a long absence and I had a look around but couldn't find anything really helpful.
You are writing the answer to the console. You use the ps1 as a function, so you should use:
return $ws
instead of
write-host $ws
I want to execute below code in the either local or remote machine whith current user.
$BackUpSqlAgentAndRemoveOldbackup = {
param([string]$AppServer,[string]$SqlInstance,[string]$BackupShare,[string]$alias)
[Environment]::UserName #I got same user name in all cases.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $SqlInstance
$backupName = 'SqlAgentJob_' + $SqlInstance + '_' + (Get-Date –format ‘yyyyMMdd_HHmm’) + '_' + $alias + '.sql'
$backupPath = join-path $BackupShare $backupName
$oldBackups = Get-ChildItem $backupShare | where { ( $_.name -like 'SqlAgentJob_*.sql' ) }
$server.JobServer.Jobs.Script() | Out-File -filepath $backupPath
foreach ( $item in $oldBackups ) { remove-item $item.fullName }
}
the #argList is
#('hafcapp-1', 'hafcsql-1', '\\Host5FileSrv\Backup\test','auto')
I notice that
this one, it works well (no -comupterName and -session)
Invoke-Command -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
this one, it throw execption (I also tried "-session", get same result)
Invoke-Command -computerName localhost -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
the exception is as below, it seems the it can not access the folder.
Cannot find path '\\Host5FileSrv\Backup\test' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\Host5FileSrv\Backup\test:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (Script:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
does anyone know how can I do if I want to add computerName or session?
(notes:[Environment]::UserName return identical user)
You have run into the double hop problem. Your credentials can be transferred to the next machine (first hop), but no further (second hop). This means that you can't use the credentials of the machine where you are executing Invoke-Command on, the remote machine (localhost) to connect to a file share (\Host5FileSrv\Backup). Even if you use localhost as computername, it is still remoting. A solution could be CredSSP. See here and here for more information.
This looks like a "second hop" remoting problem, and you'll need to configure WinRM on the computers involved to use CredSSP
http://msdn.microsoft.com/en-us/library/windows/desktop/ee309365(v=vs.85).aspx