Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

how to rename domain computers with powershell script

$
0
0
Hi all,

Our company using domain environment, and the computers had been joined to the domain,  now we need to rename the computers with new requirements.

How can i achieve it with powershell scripts

For example: abc.domain.com need to renamed to cn-w-abc.domain.com

abc = The computer serial NO. last 3 strings which already available via powershell function script(serial.ps1).


Thanks in advance.

Need help with query inbox rules

$
0
0

Hi All,
I am trying to search and find all inbox rules in exchange and the script is working good if I don't have users with multiple mailboxes. If I have user test.test  and if he has 4 mailboxes the script will fail with the The specified mailbox "some name isn't unique.

I tried to pass ID, Name, Alias, Identity and all 4 giving the same result. Only thing that is left is to try with the GUID but then I run into this error. 

Cannot convert the value of type "System.Guid" to type "Microsoft.Exchange.Configuration.Tasks.MailboxIdParameter".

Is there a way to solve this issue. The lines I run are

$mailboxes = get-mailbox –resultSize unlimited
$rules = $mailboxes | foreach { get-inboxRule –mailbox $_.alias}




start-process -verb Printto

$
0
0

Objective: Print adobe files from powershell to a specific network printer (not default printer).

$portname=\\printname\quename
Start-Process $Adobe -filepath $pdf -ArgumentList $arglist -Verb Printto($portname) -PassThru

Thanks


Creating -body parameters for Invoke-RestMethod / Invoke-PowerBIRestMethod

$
0
0

We have a lot of data sources listed on our Power BI gateway (~200) and an IS enforced policy to change passwords every 45 days. The current process is for someone to go through these data sources and input the new credentials as and when they change, obviously very time consuming. I want to be able to improve the efficiency of this process by creating a PowerShell script.

 

I'm using the officially supported Power BI PowerShell module but I'm having difficulty building the Windows version of the -Body for the Invoke-PowerBIRestMethod command.

 

The request body should be as follows;

 

{"credentialDetails": {"credentialType": "Windows","credentials": "{\"credentialData\":[{\"name\":\"username\", \"value\":\"contoso\\john\"},{\"name\":\"password\", \"value\":\"*****\"}]}","encryptedConnection": "Encrypted","encryptionAlgorithm": "RSA-OAEP","privacyLevel": "Organizational"
  }
}

Its the bit in red I cannot create, I can get;

 

{"credentialDetails": {"encryptedConnection": "Encrypted","privacyLevel": "Organizational","credentialType": "Windows","encryptionAlgorithm": "RSA-OAEP","credentials": "???"
  }
}

By using the following PowerShell;

$TEST = 
  [pscustomobject]
    @{
      'credentialDetails' = 
        @{
          credentialType = 'Windows'; 
          credentials = '???';
          encryptedConnection = 'Encrypted'; 
          encryptionAlgorithm = 'RSA-OAEP'; 
          privacyLevel = "Organizational"
        }
    } 
  | ConvertTo-Json

How do I build in the red text into the PowerShell above, I've tried various things but cannot seem to get the syntax correct.

 

Thanks

Extract group Policies of multiple Servers through PowerShell

$
0
0

Hello

I wrote a script which is supposed to gather group policies on more than 300 servers. The CSV file has just one Column and it is called IP.

# DO NOT FORGET To start Windows PowerShell with elevated rights


$IPList = Import-Csv -path "C:\Users\Administrator\Desktop\Test\ServerNames.csv" -Delimiter  ";" 
$Path = "C:\Users\Administrator\Desktop\Test\$IP.GPResult.HTML"

ForEach ($IP in $IPList)
{

Get-GPResultantSetOfPolicy -Computer $IP_ -reporttype html -path $Path
write-host $IP
} 

I know sth is wrong with the script which doesn’t connect to servers and then run the Get-GPResultantSetOfPolicy command on each server. It just gives me the result of the server which the script is running on.

It is planned to adjust the script to run once with admin right and remotely should work for other servers which the IPs are in CSV file.

That would be very helpful if someone can help me with that.

Thanks



Listing all the patches/updates installed in Windows machine

$
0
0

Hi All

I want a script to list all the patches/updates installed in my PC. I tried the below script but it does not give me complete list of patches [SQL, Visual Studio, some Office patches are not listed]

$updateSearcher = new-object -com "Microsoft.Update.Searcher"
$totalupdates = $updateSearcher.GetTotalHistoryCount()
$patchList=$updateSearcher.QueryHistory(1,$totalupdates)

Please let me know if there is any way to achieve this.

 

 


Regards Ram

Convert to GB

$
0
0

Want to convert to GB from the script below

Get-VM | ForEach-Object {
  $VM = $_
  $_.Guest.Disks | ForEach-Object {
    $Report = "" | Select-Object -Property VM,Path,Capacity,FreeSpace
    $Report.VM = $VM.Name
    $Report.Path = $_.Path
    $Report.Capacity = $_.$_.CapacityMB/1KB,0
    $Report.FreeSpace = $_.FreeSpace
    $Report
  }
}

Powershell script not running when using TaskScheduler

$
0
0

Hello,

I cannot get a simple powerhsell script to execute using the task scheduler.

I have the following parameters:

powershell.exe  -ExecutionPolicy ByPass -WindowStyle Hidden -File script.ps1

I would like the script to run for any user that is logged on to the computer. The account that I am using to test execution with has domain admin level privileges. 

The script runs fine if I execute the exact same action command manually.

The script also works if I am logged on with the domain admin account that I defined as the user to execute script.

However, if a domain user is logged on, the task scheduler does not run execute the powershell script.

Any suggestions?

Thanks!


Start-Process DirectoryNotFoundException

$
0
0

Good day.
I want to remotely run a Windows update from 1809 to 1903.
If I enter commands one by one, the computer will reboot and install the update.
Here are the commands that I enter

Enter-PSSession ComputerName-001 -Verbose

Start-Process -FilePath 'C:\$WINDOWS.~BT\Sources\SetupHost.exe' -WorkingDirectory 'C:\$WINDOWS.~BT\Sources' -ArgumentList '/finalize /update'

Get-PSSession | Remove-PSSession

But when I run these commands as a script, I get an error

The command cannot be executed because the "WorkingDirectory" parameter has an invalid value or cannot be used with this command. Enter valid data and try again.

InvalidOperation: (:) [Start-Process], DirectoryNotFoundException

DirectoryNotFoundException,Microsoft.PowerShell.Commands.StartProcessCommand

I can not overcome this problem 

I tried Invoke-Command but the process does not start.

Tell me how to make it work in the script.

I have a script works on a Windows 10 Pro Computer but not a Windows Server 2012 R12 machine

$
0
0

First I do have powershell 5.1 installed on both.
Second I do have .Net Framework 4.7 on both.
Script works without error in windows 10
Error on Server 2012 R2 VM:
Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpected error occurred on a receive."

Any help is appriciated

#Download Files
$username = "Username"
$password = "Password"

$url = "https://mywebsite-support.com/Usr/Main/3rdParty/Myzipfile.zip"
$path = "E:\Install\3rdParty\Myzipfile.zip"

$web = New-Object System.Net.WebClient
$web.Credentials = new-object System.Net.NetworkCredential($username, $password)

Try
{
$web.DownloadFile($url, $path)
}
Catch
{
$ErrorMessage = $_.Exception.Message
$ErrorMessage
}


Working with multiple or single email address

$
0
0

I need to preface my question by saying I am a beginner when it comes to PowerShell... that said, I need help.  

Here is what I am trying to accomplish:  

I have a script I built that runs tasks and at the end it will email a default user specified by a parameter string. I want to give the option in this parameter to be able to change who it gets emailed to. I want to be able to email a single email address or multiple addresses. sounds easy enough until it only emails one of the emails. If not specified I see the emails working to user1, but what if you specified -MailTo "user1@company.com,user2@company.com" I have tried for several hours different ways to do this, and they have all failed. I need it to be able to have the person running the script use 1 email address (no array needed) or multiple addresses (array needed). 

Param(
    [string]$MailTo="user1@company.com"
)

Send-MailMessage -smtpServer "smtp.company.com" -to $MailTo -From "from@company.com" -subject "Hello!" -Body "Hi there!"



-AAP (Andrew)




Using a Variable as a filter in a Where-Object

$
0
0

I have been trying to figure this out... I have a folder structure that I need to be able to pull up contents of based on user input. I have a folder named "Folder1" (for this purpose). and inside Folder1 are different folders named something like "Update_3657_June2019", "Update_3578_May2019" I also have parameters set to be able to have the user input the update number ($Version). So when the user uses "Update.ps1 -Version 3657" I want it to be able to go to the path with these folders and grab the content of that specific Update folder by looking for the folder with the $Version specified.  

This below does not work. How do I get the Where-Object to filter on a variable?

Param(
    [String]$Version
)

$TopPath="\\SERVER1\Folder1"
$AllDirs=Get-ChildItem -Path $NewPath -Directory
$Folder=($AllDirs | Where-Object {$_.Name -like '*$Version*'}).Name
$FullPath=$TopPath\$Folder
Get-ChildItem -Path $FullPath


-AAP (Andrew)

Update, insert, and delete statements for Powershell and MS Access file

$
0
0

Hi all!

I have this MS Access file which I've been able (via an tutorial) to retrieve records from.

However, I have not been able to find any article on how you can update, insert, and delete records to a MS Access file using Powershell. And so I'm wondering if anyone have articles that describe this for beginners?

Thnx in advance!


/Christian

Is SMB1 enabled on our Windows servers?

$
0
0
How to use PS to create a SMB1 report on Windows Servers? 

Outlook client Powershell Script to delete mail including Conversation History (Skype)

$
0
0

Sorry, I'm a newbie to powershell, I have found some code and pieced it together to get this far...but this code for outlook 2010 has errors and I don't know how to clear the conversation history

My organisaton have a computer on a generic windows account which is running outlook, the account has been restricted in exchange to only send internal email, however I want to delete all read email in the inbox (leaving unread untouched), delete drafts, delete outbox, delete sent items and delete conversation history, then empty the recycle bin...


Equally, there may be a better way to script this...

Would anyone be able to help?

Thank you in advance, Steve.

powershell Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy"RemoteSigned"

[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

$outlook = new-object -com outlook.application

Get-Process outlook* | Foreach-Object { $_.CloseMainWindow() | Out-Null } | stop-process –force

#Define folders

sleep 3

$namespace = $outlook.GetNameSpace("MAPI")

$DefaultFolder = $namespace.GetDefaultFolder(6)

$SentFolder = $namespace.GetDefaultFolder(5)

$OutBoxFolder = $namespace.GetDefaultFolder(4)

$DraftFolder = $namespace.GetDefaultFolder(16)

sleep 3

$DeletedItem=$namespace.GetDefaultFolder(3)

$deletedMail=$DeletedItem.Items

$emails = $DefaultFolder.Items

$Semails = $SentFolder.Items

$Oemails = $OutBoxFolder.Items

$Demails = $DraftFolder.Items

Write-Host -ForegroundColor Green "Name of Folder is $($DefaultFolder.Name)"

Write-host -ForegroundColor Green "Total item in Mail $($emails.Count)"

Write-Host -ForegroundColor Green "Total items for $($DefaultFolder.UnReadItemCount)"

Write-Host -ForegroundColor Red "Total items in $($SentFolder.Name)"

Write-Host -ForegroundColor Red "Total items in $($Semailsr.Count)"

Write-Host -ForegroundColor Red "Total items in $($OutBoxFolder.Name)"

Write-Host -ForegroundColor Red "Total items in $($Oemail.count)"

Write-Host -ForegroundColor Red "Total items in $($DraftFolder.Name)"

Write-Host -ForegroundColor yellow "Name of Folder is $($DeletedItem.Name)"

Write-host -ForegroundColor yellow "Total item in Mail $($deletedMail.Count)"

 $($Semails).delete()

 $($Oemails).delete()

 $($Demails).delete()

}

For($i=($emails.count-1);$i -ge 0;$i--){

if($emails.count -eq 1){

if(! $($emails).Unread){

 $($emails).delete()

}

}

else{

if(! $($emails)[$i].Unread -and $i -ge 0){

 $($emails)[$i].delete()

}

}

if($deletedMail.Count -gt 0){

For($j=($deletedMail.count-1);$j -ge 0;$j--){

if($deletedMail.count -eq 1){

 $($deletedMail).delete() {

else{

 $($deletedMail)[$j].delete()

}

}

}

}



getting local admins form remote machine into csv cell

$
0
0

I use invoke-command to get a list of local admins from remote systems that I'm then trying to place in an Excel's cell and failing. Problem is that my custom property which is a hash table has all the info needed when I run my script displaying it, with all groups listed as should be. The array that then collects all the props for all systems has the info as well but when it get's exported to csv with -NoTypeInformation flag and looking in my excel spreadsheed I see only the first group listed in local admins rather than all of them. Before I put my $admins variable into the property I remove whitespace by running -split '/s+'  and piping to foreach $_ + "; " to replace the comas with semicolons and then cast the result to | out-string. Still I get only the first group in my cell where it shows fine in the console. What would be the reason for that?


yaro

Powershell output from Get-ItemProperty - VersionDetails property of file does not correlate with version when browsing through GUI.

$
0
0

Hi,

Recently we needed to get the version of mpio.sys one of our servers.

I used Get-ItemProperty in Powershell to get the version, but when we browsed to the mpio.sys file in Explorer and looked at the Details tab, the values did not correlate with the values I got from Powershell. I am 100% certain that the path included in the Powershell command was correct. Can anyone provide an explanation of why this can occur?

make one checkbox disabled while another one is checked

$
0
0

Hello,

I woud like to make one checkbox disabled if another one is checked and vice versa.

I do something like that:

$pageFileCheckbox = New-Object System.Windows.Forms.Checkbox 
$pageFileCheckbox.Location = New-Object System.Drawing.Size(10,390)
$pageFileCheckbox.Size = New-Object System.Drawing.Size(150,20)
$pageFileCheckbox.Text = "Default value = 1,5*RAM"

$pageFileCheckboxNotDefault = New-Object System.Windows.Forms.Checkbox 
$pageFileCheckboxNotDefault.Location = New-Object System.Drawing.Size(10,410)
$pageFileCheckboxNotDefault.Size = New-Object System.Drawing.Size(150,20)
$pageFileCheckboxNotDefault.Text = "Particular value in GB"

if($pageFileCheckbox.checked)
{
    $pageFileCheckboxNotDefault.Enabled = $false
}
This doesnt work of course. I'd like this happen right in the form when user fills up the form. How to achieve that?

use powershell to work with dcdiag

$
0
0

Hi,

I find the following script to work with DCDIAG in english environment

function Invoke-DcDiag {
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$DomainController
    )
 
    $result = dcdiag /s:$DomainController
    $result | select-string -pattern '\. (.*) \b(passed|failed)\b test (.*)' | foreach {
        $obj = @{
            TestName = $_.Matches.Groups[3].Value
            TestResult = $_.Matches.Groups[2].Value
            Entity = $_.Matches.Groups[1].Value
        }
        [pscustomobject]$obj
    }
}

And the result is :

It works good but I'm in french language and I don't know how to do for it to work.

In english, dcdiag is like this :

In french it's like this :

I know I have to change this line :

select-string -pattern '\. (.*) \b(passed|failed)\b test (.*)'

but I don' tknow exactly what I have to change.  (passed, failed, test but not only this)


Merci de marquer comme reponses les interventions qui vous ont ete utile.

Powershell Script Automation

$
0
0

I have a script that connects to an SFTP location and synchronises a remote and Local location.  This works like a dream when i run it manually 100%.

I need to run this script every 15 mins and as such I have created a Task Scheduler Job. 

When i run the task scheduler job once created it runs but nothing happens.  

I can seem to get this job to run,  the credentials i am using are the same i created the script in and when i run manually it works it is only when i try to run the script using task scheduler it does nothing.  I am running out of ideas. 

Any assistance would be greatly appreciated.   

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>