Need help in writing EICAR content in a utf8 file using PowerShell - powershell

Basically I have file in my Windows machine of UTF8 code. Similar to this path directory and file "G:\这是一\个令人沮". And I am trying to write EICAR string (X5O!P%#AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*) to the file using PowerShell.
For regular file path it is being done like following:
#Base64 of Eicar string
[string] $EncodedEicar = 'WDVPIVAlQEFQWzRcUFpYNTQoUF4pN0NDKTd9JEVJQ0FSLVNUQU5EQVJELUFOVElWSVJVUy1URVNULUZJTEUhJEgrSCo='
if (!(Test-Path -Path $FilePath)) {
try {
[byte[]] $EicarBytes = [System.Convert]::FromBase64String($EncodedEicar)
[string] $Eicar = [System.Text.Encoding]::UTF8.GetString($EicarBytes)
Set-Content -Value $Eicar -Encoding ascii -Path $FilePath -Force
}
Tried the following suggestions didnt help :(
Executed powershell.exe "& {Import-Module C:\PROGRA~1\WindowsPowershell\Modules\new_eicar.psm1 -Force -DisableNameChecking ;New-Eicar -Path 'N:\这是一\个令人沮' -FileName 'eicar.com'; if ($?) {exit 0} else {exit 1}}". Result: {'status': 1, 'stderr': '', 'stdout': 'New-Eicar : Cannot validate argument on parameter \'Path\'. The "Test-Path $_ \r\n-PathType \'Container\'" validation script for the argument with value \r\n"N:\\\x8a\xa8T\x91~_\x84,?\\\x84,\xa6\x84\xaf\x0f\x84\xa7\xa7\x91\xfdr" did not return a result of True. Determine why the \r\nvalidation script failed, and then try the command again.\r\nAt line:1 char:116\r\n+ ... ew-Eicar -Path \'N:\\\x8a\xa8T\x91~_\x84,?\\\x84,\xa6\x84\xaf\x0f\x84\xa7\xa7\x91\xfdr\' -FileName \'eicar.com\'; if \r\n($?) {exit ...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n + CategoryInfo : InvalidData: (:) [New-Eicar], ParameterBindingVa \r\n lidationException\r\n + FullyQualifiedErrorId : ParameterArgumentValidationError,New-Eicar\r\n \r\n'}
2017-08-30 23:31:12 DEBUG ssh.py:228 (TB) 10.5.22.4>> 'powershell.exe "& {Import-Module C:\PROGRA~1\WindowsPowershell\Modules\new_eicar.psm1 -Force -DisableNameChecking ;New-Eicar -Path 'N:\这是一\个令人沮' -FileName 'eicar.com'; if ($?) {exit 0} else {exit 1}}"', timeout: 300
2017-08-30 23:31:13 DEBUG ssh.py:306 (TB) 10.5.22.4<< '{
status: 1,
stderr: ,
stdout: New-Eicar : Cannot validate argument on parameter 'Path'. The "Test-Path $_
-PathType 'Container'" validation script for the argument with value
"N:\T~_,?\,r" did not return a result of True. Determine why the
validation script failed, and then try the command again.
At line:1 char:116
+ ... ew-Eicar -Path 'N:\T~_,?\,r' -FileName 'eicar.com'; if
($?) {exit ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-Eicar], ParameterBindingVa
lidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,New-Eicar
}'

Related

Powershell Error: Cannot validate argument on parameter 'FilePath'. The argument is null or empty

I am trying to test the uninstallation of a program that is installed on my device. I am not sure what I need to do to specify the file path to this exe located on my device. Eventually this will need to be deployed organization wide, that's why I am attempting to use $PSScriptRoot. How do I specify the filepath to the exe I need deleted? It's a simple script but I keep getting the below error:
Transcript started, output file is C:\WINDOWS\TEMP\Python3.7.8Install.log
2022-10-26-03-08-47 - Install
Start-Process : Cannot validate argument on parameter 'FilePath'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\grayvi02\Downloads\UpdatePython.ps1:13 char:27
+ $Process1 = Start-Process $Install_Path -ArgumentList $Install_Args - ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Start-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartProcessCommand
2022-10-26-03-08-47 - Error - Install error with exitcode
Transcript stopped, output file is C:\WINDOWS\TEMP\Python3.7.8Install.log
$OutputFile = "$env:WINDIR\TEMP\Python3.7.8Install.log"
Writelog $Install_File = "python-3.7.8-amd64.exe"
Writelog $Install_Path = "`"$PSScriptRoot\$Install_File`""
$Install_Args = " /quiet /uninstall"
##########ERROR LOGGING#####
Function Set-WriteToLog ($Write1)
{
Write-Host "$(Get-Date -format yyyy-MM-dd-hh-mm-ss)`t-`t$Write1"
}
#########START OF SCRIPT BODY#############
Start-Transcript -Path $OutputFile
set-WriteToLog "Install $Install_File"
$Process1 = Start-Process $Install_Path -ArgumentList $Install_Args -Wait -NoNewWindow -passthru
$ErrorVal = $Process1.exitcode
If (#(0,1641,3010) -contains $Process1.exitcode)
{
Set-WriteToLog "Success - Install $Install_File with exitcode $ErrorVal"
}
else
{
Set-WriteToLog "Error - Install error with exitcode $ErrorVal"
}
Stop-Transcript
Exit $LASTEXITCODE

How do I pass multiple variables to a powershell function?

Just laying this out there. Here is my code for downloading an application and installing it.
# File Download and Install Function
function FDL($url){
# set to the default download directory; obviously can be wherever one wants
$DL = set-location $env:USERPROFILE\downloads\
# using this to capture just the filename
$FN = $url -split("/")
$FD = $FN[$FN.Length-1]
# Download File
Start-BitsTransfer -source $url -destination $DL\$FD
# Install File
Start-Process -NoNewWindow $DL\$FD -ArgumentList $args
}
PS:> FDL "https://www.kymoto.org/downloads/ISStudio_Latest.exe"
This function works perfectly every time assuming that the URL is correct!
Then I thought, what if I were to have the functionality to place the correct arguments for the installer type. So I came up with this:
# File Download and Install Function
function FDL($url,$p){
# set to the default download directory; obviously can be whereever one wants
$DL = set-location $env:USERPROFILE\downloads\
# using this to capture just the filename
$FN = $url -split("/")
$FD = $FN[$FN.Length-1]
switch ($p){
1 {" /passive /qb /norestart";break}
2 {" /sp- /silent /norestart /SUPPRESSMSGBOXES /CURRENTUSERS /NORESTART /NOCANCEL /FORCECLOSEAPPLICATION /RESTARTAPPLICATIONS";break}
3 {" /SILENT";break}
4 {" /quiet";break}
5 {" /S";break}
6 {" /Q";break}
}
Start-BitsTransfer -source $url -destination $DL\$FD
Start-Process -NoNewWindow $DL\$FD -ArgumentList $p
}
# 2 because this is an InnoSetup installer type
PS:> FDL 'https://www.kymoto.org/downloads/ISStudio_Latest.exe', 2
FAIL
Start-BitsTransfer : The number of items specified in the Source parameter do not match the number of items specified in the Destination parameter. Verify that the same
number of items is specified in the Source and Destination parameters.
At [dir]\FileDownloader Function.ps1:17 char:1
+ Start-BitsTransfer -source $url -destination $DL\$FD
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-BitsTransfer], ArgumentException
+ FullyQualifiedErrorId : StartBitsTransferArgumentException,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
Start-BitsTransfer :
At [dir]\FileDownloader Function.ps1:17 char:1
+ Start-BitsTransfer -source $url -destination $DL\$FD
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-BitsTransfer], Exception
+ FullyQualifiedErrorId : System.Exception,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
Start-Process : Cannot validate argument on parameter 'ArgumentList'. The argument is null or empty. Provide an argument that is not null or empty, and then try the
command again.
At [dir]\FileDownloader Function.ps1:20 char:50
+ Start-Process -NoNewWindow $DL\$FD -ArgumentList ($p)
+ ~~~~
+ CategoryInfo : InvalidData: (:) [Start-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartProcessCommand
No matter how I adjust this code it comes out with the same error. Any suggestions or assistance here will be greatly appreciated!
Might not be exactly what you're looking for but it should give you a hint as to approach the code for a function in PowerShell.
A few pointers, parameters in PowerShell are either Positional or Named, about_Parameters explains both concepts. Most importantly, each argument is separated by a space and not by a comma.
You can parse an URL using the Uri Class, so, for getting the file name from your address, is as simple as:
# Last segment from this Uri (index -1 from the segment array)
([uri] 'https://www.kymoto.org/downloads/ISStudio_Latest.exe').Segments[-1]
-ArgumentList from Start-Process expects string[], you can pass an array of arguments instead of a single string as shown in Example 7.
You're never capturing the output from your switch ($p), which explains the error:
Start-Process : Cannot validate argument on parameter 'ArgumentList'. The argument is null or empty.
A hash table can be used instead of a switch.
Lastly, I have added a -PassThru switch, now if you call the function with the switch activated (DownloadFile -PassThru -Uri ...), the function will output the Process instance representing the started process.
function DownloadFile {
[cmdletbinding()]
param(
[parameter(Mandatory)]
[uri] $Uri,
[parameter()]
[ValidateSet(1,2,3,4,5,6)]
[int] $Arguments,
[parameter()]
[string] $Destination = "$env:USERPROFILE\Downloads",
[parameter()]
[switch] $PassThru
)
$arg = #{
1 = '/passive', '/qb', '/norestart'
2 = #(
'/sp-', '/silent', '/norestart', '/SUPPRESSMSGBOXES'
'/CURRENTUSERS', '/NORESTART', '/NOCANCEL'
'/FORCECLOSEAPPLICATION', '/RESTARTAPPLICATIONS'
)
3 = '/SILENT'
4 = '/quiet'
5 = '/S'
6 = '/Q'
}
$destFile = Join-Path $Destination -ChildPath $Uri.Segments[-1]
Start-BitsTransfer -Source $Uri -Destination $destFile
$param = #{
FilePath = $destFile
ArgumentList = $arg[$Arguments]
NoNewWindow = $true
PassThru = $PassThru.IsPresent
}
Start-Process #param
}
DownloadFile -Uri 'https://www.kymoto.org/downloads/ISStudio_Latest.exe' -Arguments 2

how to dealing with quotes in powershell scriptblock

this code works as expected:
$var = "a123"
$script = #'
Add-Content C:\temp\test.txt -Value {{"{0} name1"}}
Add-Content C:\temp\test.txt -Value {{"{0} name2"}}
'# -f $var
$command = [scriptblock]::Create($script)
Start-Process powershell.exe -Verb RunAs -ArgumentList "-NoExit -command & {$command}" -Wait
But when I change the value of $var to "123", I get the error:
At line:1 char:49
+ & {Add-Content C:\temp\test.txt -Value {123 name1}
+ ~~~~~
Unexpected token 'name1' in expression or statement.
At line:2 char:46
+ Add-Content C:\temp\test.txt -Value {123 name2}}
+ ~~~~~
Unexpected token 'name2' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
I tried with other quotes, with casting to string but I have no solution that works. Can anyone help please?
I think I figured out, what is happening and how to work around it.
The problem is, that somehow the double quotes in your script block are lost, once the command is passed to powershell.exe and something funny happens, when the first token of your script block is not identified as a string. Compare this:
{123a name1} # Returns a script block
{123 name1} # Fails with "UnexpectedToken" exception
{$true name1} # Fails with "UnexpectedToken" exception
I have not the slightest idea, why that happens, but that is what you can do, to work around it:
$var = "123"
$script = #'
Add-Content C:\temp\test.txt -Value {{'{0} name1'}}
Add-Content C:\temp\test.txt -Value {{'{0} name2'}}
'# -f $var
The single quotes are somehow maintained when the command is passed on and the output in C:\temp\test.txt looks like this:
'123 name1'
'123 name2'

Using variable as parameter works, using source of variable fails

I found a way to get the current working directory into $dp0.
PS C:\src\powershell> Get-Content .\curdir2.ps1
$dp0 = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
Set-Location -Path $dp0
Write-Host "location is set"
Set-Location -Path [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
Write-Host (Get-Location).Path
Why is it that when I try to use the same way as a parameter to Set-Location it is an error? I think this may be something fundamental about the objects in Powershell. What do I need to know?
Set-Location : A positional parameter cannot be found that accepts argument 'C:\src\powershell\curdir2.ps1'.
At C:\src\powershell\curdir2.ps1:6 char:1
+ Set-Location -Path [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.De ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
Use parentheses.
As you can see in PS ISE that entire parameter is interpreted as a literal string otherwise.
And always use -LiteralPath instead of -Path to correctly handle directories with [] brackets.
Set-Location -LiteralPath ([IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition))
PS3.0+: cd -LiteralPath $PSScriptRoot

Powershell open Ps1 if true

What am I doing wrong here? I am trying to open a second PS1 file if True but an error is thrown (shown below).
#ABOUT
#GLOBALS
$userID = "admin"
$pswrd = "test"
$name = Read-Host 'What is your username?'
$pass = Read-Host 'And your password?' #-AsSecureString | ConvertFrom-SecureString
#$script = '.\sdsSysMain.ps1'
if($name -eq $userID -and $pass -eq $pswrd) #or blank?
{
#write-host "Well done! You're in. "
#Start-Sleep -s 5
Powershell -noexit ".\sdsSysMain.ps1"
}
elseif($name -ne $userID -or $pass -ne $pswrd)
{
write-host "Login Failed... :("
}
This is the error I'm getting:
powershell.exe : The term '.\sdsSysMain.ps1' is not recognized as the name of a cmdlet, function
At C:\Users\1234\Documents\Projects\sdsSys\sdsSysLogin.ps1:19 char:15
+ Powershell <<<< -noexit ".\sdsSysMain.ps1"
+ CategoryInfo : NotSpecified: (The term '.\sds...mdlet, function:String) [],
RemoteException
+ FullyQualifiedErrorId : NativeCommandError
, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At line:1 char:17
+ .\sdsSysMain.ps1 <<<<
+ CategoryInfo : ObjectNotFound: (.\sdsSysMain.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The error is rather self-explanatory. The script doesn't find sdsSysMain.ps1 in the current working directory. You can output the current working directory in your script like this:
(Get-Location).Path
If you want to run sdsSysMain.ps1 from the same directory as the script calling it, change this:
Powershell -noexit ".\sdsSysMain.ps1"
into this:
$scriptPath = Split-Path -Parent $script:MyInvocation.MyCommand.Path
Powershell -NoExit -File "$scriptPath\sdsSysMain.ps1"