I'm trying to get a script running that maps network drives at login. Generally, I use get-content with | convertfrom-stringdata to put my parameters (drive letter and path) in a hash.
My problem is the following:
net use /persistent:no $driveletter $networkpath
results with an error. When I replace $networkpath with the actual path (\\server\share\folder), it works.
Does anyone know what to do there? Help is greatly appreciated.
If any information is missing, I'll add it as soon as I can!
Greetings,
Blaargh
EDIT: more code for better understanding of problem
$hash = get-content C:\temp\file.txt | convertfrom-stringdata
foreach ($keys in $hash.keys) {
$hashtwo = $hash.$keys -split ("=")
net use /persistent:no $hashtwo[1] $hashtwo[0]
}
My textfile looks like this:
key = \\\\server\\share\\folder =G:
PetSerAl found the solution:
#blaargh Add Write-Host "'$($hashtwo[1])' '$($hashtwo[0])'" to be sure, that variables does not have extra space somewhere.
Related
Need some help with a substring please? I have a csv which contains file paths in column A.
These paths have .foo at the end (appended from the original query).
Is there a way to use a substring (or something else) which will search the path\text and return the content up until this point for example
C:\test folder\Folder1\Test 2\filename.abc(foo)
and return
C:\test folder\Folder1\Test 2\filename.abc
I dont really have any sample code as Im just starting out - thanks.
I am not going to write this for you but I will give you an example and some things to read to get you going. Make sure to take the tour https://stackoverflow.com/tour.
Jump in to your code by writing some code and then come ask again. These articles here will help you with what you want.
https://devblogs.microsoft.com/scripting/trim-your-strings-with-powershell/
or
https://adamtheautomator.com/powershell-split-path/
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_split?view=powershell-7.2
Here is an example I made for you
$file = (Get-ChildItem C:\Temp\dnd.txt | Select-Object -ExpandProperty name).Split('.')[0]
There are a ton of ways to do what you are asking and my example is not even a start. Write some code, define your goals and come ask again.
a different example
https://devblogs.microsoft.com/scripting/two-simple-powershell-methods-to-remove-the-last-letter-of-a-string/
$file = Get-ChildItem C:\Temp\dnd.txt | Select-Object -ExpandProperty name
$file = $file.Substring(0,$file.Length - 3)
$file
Corrected again. Please understand there are better ways to do what I did and you really need to explain what you want better.
Last one :)
Let's assume you have a file called example.csv in the c:\temp folder.
Inside the file example.csv are a bunch of paths with something you need to strip of the end and then output the results.
Contents of example.csv
head
c:\temp\fileafoo
c:\temp\filebfoo
c:\temp\filestuffcfoo
The code
$paths = $null
$paths = Import-Csv C:\temp\example.csv | ForEach-Object{
$var = $null
$var = $_.head
[PSCustomObject]#{
Corrected = $var.substring(0,$var.length - 3)
}
}
$paths
Results are
Corrected
---------
c:\temp\filea
c:\temp\fileb
c:\temp\filestuffc
And you can export this with $paths | Export-csv c:\temp\result.csv -NoTypeInformation
I want to split directory path using power shell. My full path is D:\data\path1\path2\abc.txt and i want to split it to path2\abc.txt.
Can someone let me know how can I do that.
$last2parts = "D:\data\path1\path2\abc.txt".Split("\") | Select-Object -Last 2
$last2parts -join "\"
In reply to your comment on another solution try this. Just remove your constant d:\data\path1. Then perform the split
$last2parts = "D:\data\path1\path2\abc.txt".Replace("D:\data\path1","")
$last2parts =$last2parts.Split("\") | Select-Object -Last 2
$last2parts -join "\"
Or try perhaps this if you want everything after D:\data\path1
$lastparts = "D:\data\path1\path2\abc.txt".Replace("D:\data\path1","")
$lastparts =$lastparts.Split("\")
$lastparts -join "\"
$PathAsString = "D:\data\path1\path2\abc.txt"
[System.IO.Path]::Combine($(Split-Path -leaf $(Split-Path $PathAsString)),$(Split-Path -leaf $PathAsString))
Uses the system's delimiter rather than specifying Windows' '\' character.
Honestly if I knew this was only ever going to run on Windows systems I'd go with #ChiliYago's answer since you can't put the path delimiter character in a file or directory name like you can in Linux.
Sorry for the super late post! I think you may have got the fix. But here is something you can try.
You can try using the substring() function as well.
$fullPath = "D:\data\path1\path2\abc.txt"
$rootPath = "D:\data\path1\"
$filePath = $fullPath.substring($rootPath.length, ($fullPath.length - $rootPath.length) )
Something like this may help you.
Here on Stack Overflow when you ask a question, please post some code that you've tried already and the results you're getting. We help you with code you've already tried, we aren't here to write it for you (:
However... I would start here: Link
That will get you started. You can also do the following in a console to get some info on the command Split-Path
Get-Help Split-Path -Example
After you put something together on your own, you can edit your post to include what you've tried and then you will be more likely to get an accurate response for your particular situation. Good luck and good coding!
I am trying to parse a string using [regex]::matches. I am able to split the words but i am having trouble with the open and close paren. Could someone help me and explain what I am doing wrong? Thank you in advanced.
$results = "All domain controllers have migrated successfully to the Global state ('Start')."
[regex]::Matches($results , "\w+['a-z']") | foreach-object {$_.value}
Tweaking #TheMadTechnician's regex just a bit, "\('([^\)']*)'\)" will get the word between (' and '), without the quotes. I use the -match operator below. The result you want will be in the $matches[1] variable.
PS> $results = "All domain controllers have migrated successfully to the Global state ('Start')."
PS> $results -match "\('([^\)']*)'\)"
True
PS> $matches[1]
Start
So, this was the only way I could figure out how to get this. If others are able to give a simpler solution I am all ears. But for now, this is the way I got it to work
([regex]::Matches($results , '\w+[('')^]' ) | foreach-object {$_.value }).replace("'", "")
I have a csv file that contains fields with values that begin with "$" that are representative of variables in different powershell scripts. I am attempting to import the csv and then replace the string version of the variable (ex. '$var1') with the actual variable in the script. I have been able to isolate the appropriate strings from the input but I'm having difficulty turning the corner on modifying the value.
Example:
CSV input file -
In Server,Out Server
\\$var1\in_Company1,\\$var2\in_Company1
\\$var1\in_Company2,\\$var2\in_Company2
Script (so far) -
$Import=import-csv "C:\temp\test1.csv"
$Var1="\\server1"
$Var2="\\server2"
$matchstring="(?=\$)(.*?)(?=\\)"
$Import| %{$_ | gm -MemberType NoteProperty |
%{[regex]::matches($Import.$($_.name),"$matchstring")[0].value}}
Any thoughts as to how to accomplish this?
The simplest way to address this that I could think of was with variable expansion as supposed to replacement. You have the variables set in the CSV so lets just expand them to their respective values in the script.
# If you dont have PowerShell 3.0 -raw will not work use this instead
# $Import=Get-Content $path | Out-String
$path = "C:\temp\test1.csv"
$Import = Get-Content $path -Raw
$Var1="\\server1"
$Var2="\\server2"
$ExecutionContext.InvokeCommand.ExpandString($Import) | Set-Content $path
This will net the following output in $path
In Server,Out Server
\\\\server1\in_Company1,\\\\server2\in_Company1
\\\\server1\in_Company2,\\\\server2\in_Company2
If the slashes are doubled up here and you do not want them to be then just change the respective variable values in your script of the data in the CSV.
Caveat
This has the potential to execute malicious code you did not mean too. Have a look at this thread for more on Expanding variables in file contents. If you are comfortable with the risks then this solution as presented should be fine.
Maybe I misunderstood, but do you need this?
$Import=import-csv "C:\temp\test1.cvs"
$Var1="\\server1"
$Var2="\\server2"
Foreach ($row in $Import )
{
$row.'In Server' = ($row.'In Server' -replace '\\\\\$var1', "$var1")
$row.'Out Server' = ($row.'Out Server' -replace '\\\\\$var2', "$var2")
}
$import | set-content $path
can someone please check this script and point me to the right direction. I'm not getting any errors though but script is not working as expected. I'm trying to achieve a shortcut target changed based on logged user.My powershell skills are basic and i'm sure must be missing some logic here:-
#$shell = new-object -com wscript.shell
$loguser="username"
$link ="test1.lnk"
$oldtarget=$link.tragetpath
$oldpath="c:\notepad.exe"
Get-ChildItem -Filter $link -Recurse
if ($oldtarget -eq $oldpath)
{
$csvfile=Import-csv "c:\test.csv"
$newtarget=$row.newpath
$user=$row.user
(get-Content $csvfile) | foreach-object {$_.$user -match $loguser} | -replace $oldtarget $newtarget
}
$link.SaveInfo
A way better way to modify shortcuts is to get rid of the VBScript shell and use P/Invoke. Take a look at sample code in Poshcode. It contains some 1200 lines of code, so I won't copy it here.