I'm trying to read a certain line from a text file using powershell, which can then be used to run with netdom to rename each DC. The line is always line number 3 and starts with Servername= . I need to grab the text after the equals sign to then use with netdom. It was working at first, but netdom would complain about the syntax. Is this because it is a string?. Now servername is returned as the full line:
C:\config.txt:3:ServerName servername
and not just the servername.
$servername = Select-String -Path "C:\config.txt" -Pattern "servername="
$servername = $servername.tostring().split("=")
netdom renamecomputer localhost /NewName:$servername /force
I think you have to append [1] to the second line in order to select the split string that you need i.e:
$servername = $servername.tostring().split("=")[1]
Related
I'm creating a script that I can use to set up new user account in AD.
Early in the batch file I have a variable that is saved like this -
set state=%pspath% "St" -Value 'Gloucestershire'
pspath is populated later in the batch when the user is actually being created this part -
set pspath="Set-ItemProperty -Path 'CN=%firstname% %lastname%,%ou%' -Name"
powershell -nologo Import-Module ActiveDirectory;Set-Location AD:;%state%;
Firstname, lastname and ou is all populated without a problem, but in that second line when I'm using the %state% variable, %pspath% is ignore and the command comes out as
powershell -nologo Import-Module ActiveDirectory;Set-Location AD:;"St" -Value 'Gloucestershire'
instead of what it should be -
powershell -nologo Import-Module ActiveDirectory;Set-Location AD:;Set-ItemProperty -Path 'CN=%firstname% %lastname%,%ou%' -Name "St" -Value 'Gloucestershire'
How do I get all the variables to populate in the command properly instead of %pspath% being skipped?
I need to duplicate file many times I have a list of product numbers that need to be used as part of the new file name -- so example;
original file called photo.main.jpg
I need to copy the photo.main.jpg file many times (I am hoping to put the names to substitute in a file to read)
I have product names say 123, 456, 789, 345, 221 in the file and the product name must replace the word "photo" in the file.
this scenario i would want 5 new files called 123.main.jpg, 456.main.jpg, 789.main.jpg, 345.main.jpg and 221.main.jpg
I am hoping to do in Windows command prompt -- can someone help?
While this can be done in a cmd shell, PowerShell provides access to
regex processing that can make it very flexible.
The $replpat regex can be anything that provides what the
regex in the Copy-Item command needs. Using $matches is not required.
$orgfile = 'photo.main.jpg'
$prodfile = '.\prodlist.txt'
$replpat = '[^\.]*(.*)'
$ismatch = $orgfile -match $replpat
$filebase = $matches[1]
Get-Content -PSPath $prodfile |
ForEach-Object {
Copy-Item -Path $orgfile -Destination "$_$filebase" -WhatIf
}
This question already has answers here:
How to properly -filter multiple strings in a PowerShell copy script
(5 answers)
Closed 6 years ago.
I have this script and it's working 100% , but only for a single item
I want to loop the script and get content from a txt file
You see, my scipt search for a specific file and copy it to an existing folder with the same name of the file.
So what I want is to get the folder's name and the file's name from 2 txt files and loop the script
I have manage to get the content from the txt files but I can't loop the script if I add a second line with new values in my txt files.
I always get the error:
Get-ChildItem : Cannot convert 'System.Object[]' to the type
'System.String' required by parameter 'Filter'. Specified method is
not supporte d.
Ok this is my script:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned
# Setup source and destination paths
$Src = '\\192.168.0.216\home\'
$Dst = 'C:\TEST\120629B\'
# Wildcard for filter
$Extension = '120629B.jpg'
# Get file objects recursively
Get-ChildItem -Path $Src -Filter $Extension -Recurse |
# Skip directories, because XXXReadMe.txt is a valid directory name
Where-Object {!$_.PsIsContainer} |
# For each file
ForEach-Object {
# If file exist in destination folder, rename it with directory tag
if(Test-Path -Path (Join-Path -Path $Dst -ChildPath $_.Name))
{
# Get full path to the file without drive letter and replace `\` with '-'
# [regex]::Escape is needed because -replace uses regex, so we should escape '\'
$NameWithDirTag = (Split-Path -Path $_.FullName -NoQualifier) -replace [regex]::Escape('\'), '-'
# Join new file name with destination directory
$NewPath = Join-Path -Path $Dst -ChildPath $NameWithDirTag
}
# Don't modify new file path, if file doesn't exist in target dir
else
{
$NewPath = $Dst
}
# Copy file
Copy-Item -Path $_.FullName -Destination $NewPath
}
Ok this is what I have change and worked but is only working with one record
$Src = '\\192.168.0.216\home\'
$Dst = Get-Content 'C:\TEST\path.txt'
# Wildcard for filter
$Extension = Get-Content 'C:\TEST\file.txt'
The error message is telling you the problem, you can't use an array as the filter for get-childitem. you can probably nest a where-object filter inside of a foreach loop but the easiest way to accomplish what you are trying to do is going to be to loop through your extension filters and then run your loop inside of that loop. so wrap your entire Get-ChildItem loop in a Foreach loop as below.
Foreach($e in $extension){
*Your Code Here*
}
Of cource make sure to change the -Filter parameter of your Get-ChildItem from $Extension to $e
Like error says, -Filter expects a single string. Get-Content would be returning an object array for files with more than one line.
Since you are also using -Recurse consider using -Include instead of -Filter since it supports arrays of stings. This should without changing your input file or adding any other post processing. From [MSDN]
Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt. Wildcards are permitted.
Get-ChildItem -Path $Src -Include $Extension -Recurse
Note:
The Include parameter is effective only when the command includes the Recurse parameter or the path leads to the contents of a directory, such as C:\Windows*, where the wildcard character specifies the contents of the C:\Windows directory.
Same goes for -Exclude as well
Thanks for viewing my question. I was unable to find any information online in regards to my question. I also have very basic experience in this area.
PowerShell Script:
-Query folder for files (list?)
-Move file based on filename to folder with same name. (Move with pipe to query?)
-Move will also parse second part of file name to include subsequent matching folder name for destination folder.
Files will contain many separate names so the move has to be on a loop.
Ex. File - "Name 1"
Scripts excutes moves file to folder with "name" then to subfolder "1".
Just to be clear there will be multiple names and numbers so multiple destination paths. Basically every file will have a different destination but the destination will correlate to the file name. If there is a language more accessible for this function please let me know.
Something like the following will get you started
$files = Get-ChildItem -File
foreach($f in $files) {
$dirname = $f -split " " -join "\"
New-Item -ItemType Directory -Path ".\$dirname"
Move-Item $f $dirname
}
I have a PowerShell script which installs a patch (contains set of files to be added) on a customer machine. For this, I have created a batch file which executes this PowerShell script.
For the customer to run this batch file, the PowerShell script file must be placed onto the customer machine as well.
The PowerShell script is in text format, which can be read and understood by the customer easily.
Can we convert this script file into some non-readable format (e.g. bin or exe), so that it is not readable by the customer?
You can convert the script to Base64 encoding, so that it's not immediately readable. To convert a PowerShell script file to a Base64 String, run the following command:
$Base64 = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes('c:\path\to\script file.ps1'));
To launch the Base64-encoded script, you can call PowerShell.exe as follows:
powershell.exe -EncodedCommand <Base64String>
For example, the following command:
powershell.exe -EncodedCommand VwByAGkAdABlAC0ASABvAHMAdAAgAC0ATwBiAGoAZQBjAHQAIAAiAEgAZQBsAGwAbwAsACAAdwBvAHIAbABkACEAIgA7AA==
Will return the following results:
Hello, world!
I tried the solution proposed by #TrevorSullivan, but it gave me error
The term '????' is not recognized as the name of a cmdlet, function,
script file or operable program...
As I found out later there was a problem with bad encoding. I found somewhere another approach and when I combined those two, I got working PS command:
$Base64 = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes([System.IO.File]::ReadAllText("script.ps1")))
Then I can redirect the result to file:
$Base64 > base64Script.txt
from where I just copy the encoded command and paste it here instead of <Base64String>:
powershell.exe -EncodedCommand <Base64String>
and it works without any problem.
Thanks guys for your posts. I took #Frimlik's post and created my own script to automate the process. I hope this helps someone.
Save the script to a ps1 file and run it.
Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
Function EncodePS1ToBat {
$ScriptToEncode = Get-FileName
# Encode the script into the variable $Base64
$Base64 = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes([System.IO.File]::ReadAllText($ScriptToEncode)))
# Get the path and name to be used as output
$filePath = Split-Path $ScriptToEncode -Parent
$fileName = (Split-Path $ScriptToEncode -Leaf).Split(".")[0]
# Output the encoded script into a batch file on the same directory of the origial script
"#echo off`n powershell.exe -ExecutionPolicy Bypass -EncodedCommand $Base64" |
Out-File -FilePath "$filePath\$fileName`_Encoded.bat" -Force -Encoding ascii
}
# Call the funtion to encode the script to a batch file
EncodePS1ToBat