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

Invoke-Command HRESULT 0x80072020

$
0
0

Hi All,

I am trying the run an invoke command using domain credentials to query a list of GPOs. The error is

An operations error occurred. (Exception from HRESULT: 0x80072020)
+ CategoryInfo : NotSpecified: (:) [Get-GPO], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.GroupPolicy.Commands.GetGpoCommand
+ PSComputerName : localhost

And the code is below

$job = Invoke-Command -ComputerName localhost -ArgumentList $DomainOU -ScriptBlock {
Import-Module GroupPolicy ;
$DomainFqdn = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() ;
$dctx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext -ArgumentList "Domain",$DomainFqdn ;
$DomainController = [System.DirectoryServices.ActiveDirectory.DomainController]::FindOne($dctx) ;

Get-GPO -All -Domain $DomainFqdn.Name -Server $DomainController.Name

} -asJob -Credential $credential
wait-job -id $job.Id
Receive-Job $job.Id


Date in filename in a export

$
0
0

I want to have in csv file the date and time from today , how can help me ?

Get-Childitem -path D:\acr-share\AOP\EPL\*\operation -filter *.epl -recurse | Select Directory,Name,CreationTime,Lastwritetime  | Export-csv -path C:\Users\MK401065\Documents\report-{Date!!!}.csv -Encoding ascii -NoTypeInformation


DeLange

Appending info to the telephone (notes) tab in AD

$
0
0

Hi everyone, 

I’m trying to create a script that adds note to the telephone (notes) tab of an AD user. 

I have this script: 

{

Import-module activedirectory

Get-ADuser -Identity $user -Server $domain -Properties info |

Set-ADuser -Replace @{info=“ `r`n Account Modified as per $request”}

}

this script works, however it removes whatever notes were in the telephone tab previously. Is there a way to add the new notes from the script without removing the old notes? 

Thanks


Audit Success Logon Log

$
0
0

Hi everyone,

I hope I explain myself clearly.

I have server(remote server) 100+ users connect to it. We have move over to a web app so no need for RDP connections.

I want to run a powershell script to see who has logged on to the RDP server in the last to months. A timestamp and Name will be sufficient.

Thanks in advance

Claude

Adding number of words with powershell command and sending email

$
0
0

I added following powershell command to scheduled tasks to check for computers that are turned on every night.
I don't want to count how many "true" counts there are for this csv file in total. Is there any command I can add to file or as name of file, how many "true" in total?

Also, how do I send these csv files by email each time they occur?

$props = @{
    Date = Get-Date
    ComputerName =''
    Online = $false
}

Get-ADComputer -Filter * | ForEach {
    
    $props.Online = $false
    $props.ComputerName = $_.Name

    If (Test-Connection $_.Name -Count 1 -Quiet) {

        $props.Online = $true

    }

    New-Object PsObject -Property $props

} | Export-Csv C:\Users\User\Desktop\OnlinePC_$((Get-Date).ToString('dd-MM-yyyy_HH-mm')).CSV -NoTypeInformation

Office 365 Bulk aliases removal Exchange Online(Office 365)

$
0
0

Good morning,

I have 05 domains registered at office 365, where the main domain is XXX.com.br.

Acidentally, I ran the following script, adding the domain YYY.com.br as alias in all this accounts.

$ users = Get-Mailbox
foreach ($ a in $ users) {$ a.emailaddresses.Add ("$ ($ a.alias) @ YYY.com.br")}
$ users |% {Set-Mailbox $ _.Identity-EmailAddresses $ _.EmailAddresses}

If we wan the following command:

Get-Mailbox | where {$ _.Name-like "* allan.lago *"-and $ _.EmailAddresses-like "* XXX.com.br *"} | fl Name, alias , EmailAddresses

The result are:

Name: allan.lago
Alias​​: allan.lago
EmailAddresses: {smtp: @ allan.lago YYY.com.br, SMTP: @ allan.lago XXX.com.br, smtp: @ allan.lago XXX.onmicrosoft.com}

I'm trying to remove these aliases from SOME (others have ZZZ.com.br as the primary domain and we dont need to remove from YYY.com.br from those) accounts via powershell using the following script:

$ users = Get-mailbox | where {$ _.emailaddresses-like "* XXX.com.br *"}
foreach ($ a in $ users) {$ a.emailaddresses.Remove ("$ ($ a.alias) @ YYY.com.br")}
$ users |% {Set-Mailbox $ _.Identity-EmailAddresses $ _.EmailAddresses}

But im not getting any results..

If anybody knows what to do.. please let me know =)

Need PowerShell command to fetch user's "member of" groups and their "Notes" & "Managed by" information in CSV File

$
0
0

Hi All,

Thanks in Advance. I'm frequently asked to fetch particular user's all "member of" groups and their owner information that situated in each group's "Notes" & "Managed by" options. So please help me by giving PowerShell command or Script as that output is given in CSV file.

Update-AdmPwdADSchema: The user has insufficient access rights (how do I add a server parameter)?

$
0
0

I'm trying to run this command for LAPS:

 Update-AdmPwdADSchema

I am part of enterprise admins, schema admins and domain admins yet I can't run this as I get an insufficient rights error. I am running this as powershell admin on the FSMO schema master. Another thread mentioned to add the -server parameter but I am not sure how to do this.

 Update-AdmPwdADSchema -Server 'serverA' tells me that server is not a valid parameter. I can't find ANY real resources on how to add this via powershell.


Does not working 100% of the time: Get-ADPrincipalGroupMembership : Directory object not found

$
0
0

Hello,

Looking to see if anyone can see where my issue is coming from. I have a script that transitions employees to different departments in our domain. There is a portion of the script where all current access is stripped from the account and the new department access is applied. Before removing the access I have the portion of the script below to export all the users group membership into a csv, which I then attach to an email sent to the manager. (incase they need to request and additional access)

It happens more times than I'd like but i get the error message:

Get-ADPrincipalGroupMembership : Directory object not found
At E:\PowerShellScripts\28AUG2019_Re_Hire_Transitions.ps1:857 char:5
+     Get-ADPrincipalGroupMembership -Identity $UserN | select Name | S ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Test.User:ADPrincipal) [Get-ADPrincipalGroupMembership], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADPrinc 
   ipalGroupMembership

the Permissions weren't exported into the csv for the previous access, but the new access csv goes through with no issues.

$UserN = Read-Host "Please Provide the Users UserName..."

#Find current access and export to CSV to email to manager
Get-ADPrincipalGroupMembership -Identity $UserN | select Name | Sort Name `
| Export-Csv "E:\PowerShellScripts\Transitions\Previous_Access.csv" -notypeinformation -Append 

#Find new access and export to CSV to email to manager
Get-ADPrincipalGroupMembership -Identity $UserN | select Name | Sort Name `
| Export-Csv "E:\PowerShellScripts\Transitions\New_Access.csv" -NoTypeInformation -Append


Is it possible with select-xml to....

$
0
0

select a xml tag AND its contents inclusing the Tag start and  end itself

<Start>

Random Text here

</Start>

im trying

select-xml -path $my path -xpath //Start | select-object -expandproperty node

it returns 'Random Text here' but not the two tags <Start></Start>

Is this possible?

Thank You

Powershell command to disable dial in button in AD

$
0
0

I'm having bulk account disabling request,

I have to set dial in as deny access in AD. please provide power-shell script.

Powershell command to update description in AD

$
0
0
Powershell command to update description in AD

Windows Server 2008: PowerShell (Get all list of OU, Users, Computers, GPO in ADDS)

$
0
0

Hi,

any documentations, ideas, links, videos that can help me the scripts for what i need to do? Apparently, the script Get-ADOrganizationalUnit doesn't read by Windows Server 2008.

Thanks

take date from file and update time stamp to match

$
0
0

Hi All!

First post... 

I'm still learning powershell here so call me a noob :)

I've been working on a script to encode some videos to crop black bars out of the 4:3 ones. I got everything I need to work but powershelling a timestamp to update the files to have the date of the video.

Example : 1992-04-18 - Filename.mp4 I want to take the 1992-04-18 from the name and update the timestamp from like today's date and have it the date of the video. This is needed for my media center to read the file and sort from metadata of the file it will use to watch things in order.

I know there's a script that you can hard code the date

$(Get-Item '$filename.CreationTime=$(Get-Date "1992-04-18 06:00 pm");

but i'm going to use "ForEach" to pull the files from a directory and put them in a txt file to be called and ran with my script. 

Is this possible? 

Resulting Excel files from this PowerShell script are blank

$
0
0

I am writing the following script to take SQL Server results and put them in an Excel file.  The Excel files create successfully but the file is blank with no values.  I have confirmed that the SQL query is in fact returning results.

Any ideas what I could be missing here?

$FileName = "C:\Users\Me\Documents\TestFile.xlsx";
$ConnectionString = "Our DB connection string"
$SqlQuery = @"
SELECT Id
FROM dbo.Orders
WHERE OrderExpiry IS NULL
AND ReturnPeriod IS NULL
AND Returned IS NULL"@;

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = $ConnectionString;

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $SqlQuery;
$SqlCmd.Connection = $SqlConnection;
$SqlCmd.CommandTimeout = 60

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];


$xlsObj = New-Object -ComObject Excel.Application;

## – Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0;
$xlsWb = $xlsobj.Workbooks.Add();
$xlsSh = $xlsWb.Worksheets.item(1);

## – Build the Excel column heading:
[Array] $getColumnNames = $DataSetTable.Columns | Select ColumnName;

## – Build column header:
[Int] $RowHeader = 1;
foreach ($ColH in $getColumnNames)
{
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true;
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName;
$RowHeader++;
};

## – Adding the data start in row 2 column 1:
[Int] $rowData = 2;
[Int] $colData = 1;

foreach ($rec in $DataSetTable.Rows)
{
foreach ($Coln in $getColumnNames)
{
## – Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@";

## – Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = `
$rec.$($Coln.ColumnName).ToString();
$ColData++;
};
$rowData++; $ColData = 1;
};

## – Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange;
$xlsRng.EntireColumn.AutoFit();

## – Saving Excel file – if the file exist do delete then save
$xlsFile = $FileName;

if (Test-Path $xlsFile)
{
Remove-Item $xlsFile
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
}
else
{
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
};

## Quit Excel and Terminate Excel Application process:
$xlsObj.Quit(); (Get-Process Excel*) | foreach ($_) { $_.kill() };

$SqlConnection.Close()


How to automate Print to PDF

$
0
0

Hi

I have a folder with n number of outlook message files with extension ".msg". The content of these files should be converted to PDF without altering its format using Microsoft Print to PDF option and the output files should be saved to a folder with .pdf extension automatically.

Any help on this?

Note: I have already tried using below script and it prints only blank pages in PDF.

functionConvertTo-PDF {
	param(
		$TextDocumentPath)Add-Type-AssemblyNameSystem.Drawing
	$doc =New-ObjectSystem.Drawing.Printing.PrintDocument
	$doc.DocumentName= $TextDocumentPath
	$doc.PrinterSettings=new-ObjectSystem.Drawing.Printing.PrinterSettings
	$doc.PrinterSettings.PrinterName='Microsoft Print to PDF'
	$doc.PrinterSettings.PrintToFile= $true
	$file=[io.fileinfo]$TextDocumentPath
	$pdf=[io.path]::Combine($file.DirectoryName, $file.BaseName)+'.pdf'
	$doc.PrinterSettings.PrintFileName= $pdf
	$doc.Print()
	$doc.Dispose()}

Thanks.


Start-Transcript threw InvalidOperationException

$
0
0

Got this exception as part of a script, wondering what are the chances which are causing this exception ?

$logFilePath='ReleaseTranscript-10.02.02.txt'

+ Start-Transcript -Path $logFilePath -append
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Start-Transcript], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.StartTranscriptCommand


Aravind aravindl.blogspot.com

Cross Domain Group Nesting

$
0
0

I'm working in a large AD environment with a root domain with several sub-domains.  I am doing an analysis of groups with cross domain sub-groups and members.  Looking for a script that will show me the nesting structure of a group with cross domain sub-groups.  I have found a couple scripts that work in a single domain, but break down when dealing with cross domain nested groups.

Thanks

Poswershell line chart

$
0
0

Hi All,

I'd like to create a line chart with Powershell + Windows charting. The process would be this: I query the system date as "yy.mmmm.dd" and the system time as "hh:mm", separatedly (you'll see why). Furthermore, I query the stage of one specific port and the number of connections on this port. I export all this four datas into a .csv file with -append for later examination. Then, I open this .csv file and import only the 5 latest "time" and "connection number". I'd like to create the chart so, that the Title holds the actual chart title, plus the date, plus the stage of the port (because I haven't found any athor place where I could show them, like header, footer, remark, anything). Now, the Y-axis shows the query of connection numbers and the X-axis shows the timepoints when the queries have been made (say, in 5 minutes intervals). Below is my code so far. my problem is, that I'm getting an empty chart, showing only the title field. What am I doing wrong?

Thanks in advance.

-------------------------------------------------------------------

Add-Type -AssemblyName System.Windows.Forms.DataVisualization

Try{
    $Date = Get-Date -f "yyyy.MMMM.dd."
    $Time = Get-Date -f "HH:mm"
        
    $connection = New-Object Net.Sockets.TcpClient
    $connection.Connect("ipaddress","portnumber")
    if($connection.Connected)
    {
        "Port is connected"
    }
    else
    {
        "Port is disconnected"
    }

    $connection_num = Get-NetTCPConnection | Where-Object { $_.LocalAddress -eq "ipaddress" -and $_.LocalPort -eq "portnumber"} | Select-Object LocalAddress, LocalPort | Measure-Object | % {$_.Count}
        
    $report = New-Object psobject
    $report | Add-Member -MemberType NoteProperty -Name Date -Value $Date
    $report | Add-Member -MemberType NoteProperty -Name Time -Value $Time
    $report | Add-Member -MemberType NoteProperty -Name Connection -Value $connection.Connected
    $report | Add-Member -MemberType NoteProperty -Name Connection_num -Value $connection_num
    
    $report | Export-Csv -Append -Path Path\linechart.csv -NoTypeInformation
}

Catch{
    Throw $_}


Try{
    if($connection.Connected)
    {
        
        $msg = "Port connected"
    }
    else
    {
        $msg = "Port disconnected"
    }

    $chart1 = [System.Windows.Forms.DataVisualization.Charting.Chart]::New()
    $chart1.Size = '1700,900'
    $chart1.Titles.Add([System.Windows.Forms.DataVisualization.Charting.Title]::New())
    $chart1.Titles[0].Font = "Arial, 24pt"
    $chart1.Titles[0].Text = "Monitoring  " + "---  " + $Date + "   " + "   " + $msg
    $chart1.ChartAreas.Add([System.Windows.Forms.DataVisualization.Charting.ChartArea]::New("Default"))
    $chartarea.Name = "ChartArea1"
    $chartarea.AxisX.Interval = 10
    $chartarea.AxisY.Interval = 5
        
    $datasource = @{
        "Conn" = ((Import-Csv Path\report.csv) | Select Time, connection_num) | Select -Last 5
    }
    
    [void]$chart1.Series.Add("Data")
    $chart1.Series["Data"].ChartType = "Line"
    
    foreach ($datapoint in $datasource) {
    $x = [int]$datapoint.Connection_num
    $y = [string]$datapoint.Time
    $chart1.Series["Data"].Points.addxy($x,$y)
    }

    $imageFile = "Path\linechart.png"
    $chart1.SaveImage($imageFile,"PNG")
}
Catch{
    Throw $_}

Querying Terminal Server

$
0
0

Hello All,

We have 4 domains, from each domain I am trying to extract the Terminal services records. I am able to get the details after

providing the servers and querying each servers from the input file.

Can we query on domain level rather providing the server extract from each domain.

foreach($_ in (Get-Content C:\PowerShell\server-list.txt)){

write-host("Attemping to get server objects in " + $_ + ".")

Try {

Get-WmiObject -Namespace "root\CIMV2\TerminalServices" -Class "Win32_TerminalServiceSetting" -ComputerName $_ | select __SERVER, TerminalServerMode | Export-Csv -Append C:\PowerShell\Term-Servers.csv

} catch [System.Exception] {

write-host("Failed to get server objects in " + $_ + ".")

}


}


Thanks HA

Viewing all 21975 articles
Browse latest View live


Latest Images

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