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

get-process and UserName

$
0
0
Hi,
I'm trying to list all/some process and need to include the username since the script has to run in a terminal server environment. It works using WMI (Get-WmiObjectWin32_Processand GetOwner()) but get-process provides some more attributes I need to export to  a logfile.

Accoring to MSDN there is a property called UserName in the StartInfo object, but the value is always empty, when executing this script:

get-process

outlook | select-object id, path, @{Name="UserName";Expression = {$_.StartInfo.UserName}}

What's wrong? I am fairly new to PS, so is this the correct way of reading that property?


Thanks, regards

Execution Policy failing

$
0
0

Hi all

One of my SQL jobs which is related to Ps has just started to fail, I think its environment related as thesame code works on all other servers. Ironically, I  run the code below and then it fails also.

Get-ExecutionPolicy gives the error below.

Get-ExecutionPolicy : Generic failure
At line:1 char:1+ Get-ExecutionPolicy+ ~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Get-ExecutionPolicy], ManagementException+ FullyQualifiedErrorId : System.Management.ManagementException,Microsoft.PowerShell.Commands.GetExecutionPolicyCo
   mmand

Set-executionpolicy Remotesigned give the error below.

Set-ExecutionPolicy : Generic failure
At line:1 char:1+ Set-ExecutionPolicy+ ~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Set-ExecutionPolicy], ManagementException+ FullyQualifiedErrorId : System.Management.ManagementException,Microsoft.PowerShell.Commands.SetExecutionPolicyCo
   mmand


Duplicate AD Object Without "Active Directory" PS Tools

$
0
0

Hello All,

I need to know of a simple way to duplicate an Active Directory object (in this case a pkiCertificateTemplate), in a few lines of code as possible.  "Lain Robertson" posted a very elegant solution, but it won't work in cases where the "AD PS Tools" are not present on the server.  To my understanding, this PS add-in is not available on Windows 2008 and 2008 R2.  Does anyone know of a simple way to do this?  Below is the script and the reference page.

Param(
  [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, mandatory = $true)] $Name,
  [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, mandatory = $true)] $NewName
)

try {
  Import-Module -Name ActiveDirectory -Verbose:$false;

  $oRootDSE = Get-ADRootDSE;
  Write-Verbose -Message ("Connected to domain controller: "+ $oRootDSE.dnsHostName);


  try {
    # Pull the template attributes from the schema definition.
    $templateAttributes = (Get-ADObject -Identity ("CN=PKI-Certificate-Template,"+ $oRootDSE.schemaNamingContext) -Properties *).systemMayContain;
    Write-Verbose -Message (("Schema_attributes: "+ [System.String]$templateAttributes) -replace " ", "`n  " -replace "_", " ");

    # Include the revision attribute.
    $templateAttributes.Add("revision") | Out-Null;

    # Attempt to grab the original template.
    $originalCertificate = Get-ADObject -Identity ("CN=" + $Name + ",CN=Certificate Templates,CN=Public Key Services,CN=Services," + $oRootDSE.configurationNamingContext) -Properties $templateAttributes -Server $oRootDSE.dnsHostName;
    Write-Verbose -Message ("Found template: "+ $originalCertificate.distinguishedName);

    # Rename the display name prior to calling New-ADObject, as it's understandly not included in its renaming process.
    $originalCertificate.displayName = $NewName;

    # Ensure that msPKI-Cert-Template-OID is unique.
    do {
      $secondLast = (Get-Random).ToString();
      $Last = (Get-Random).ToString();
      $newOID = ($originalCertificate."msPKI-Cert-Template-OID" -replace "(\.[0-9]*){2}$", "") + "." + $secondLast + "." + $Last;
    } while ((Get-ADObject -Filter { msPKI-Cert-Template-OID -eq $newOID } -SearchBase ("CN=Certificate Templates,CN=Public Key Services,CN=Services,"+ $oRootDSE.configurationNamingContext ) -SearchScope OneLevel) -ne $null);

    # Assign the new msPKI-Cert-Template-OID value.
    $originalCertificate."msPKI-Cert-Template-OID" = $newOID;

    # Call New-ADObject to create the new template.
    New-ADObject -Name $NewName -Type ($originalCertificate.objectClass) -Instance $originalCertificate -Path ($originalCertificate.DistinguishedName.Substring($originalCertificate.DistinguishedName.IndexOf(",")+1));
    Write-Verbose -Message ("Template "+ $Name +" successfully duplicated using the new name of "+ $NewName +".");

  } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
    Write-Error -Message ("Failed to find a template named "+ $Name);
    exit;
  } catch [System.UnauthorizedAccessException] {
    Write-Error -Message "Access denied. You do not have the correct permissions to create the new certificate template.";
    exit;
  } catch {
    Write-Error -Message ("Unhandled exception occurred.");
    exit;
  }
} catch {
  Write-Error -Message "Failed to load the Active Directory management module."
}

REF: New Powershell Template Read Only in Certificate Manager


- Rashad Rivera www.omegusprime.com


How to exclude hidden users$ from query results.

$
0
0

Hi All

I am trying to use the following code to total enabled users BUT no include the hidden accounts. I have tried using the SamAccountName, SamAccountType, Name and nothing seems to be working for me. I am running ISE as Administrator with a high priviledge account. Please help :)

get-aduser -filter * -Properties * | where { $_.sAMAccountType -ne "805306370"} | select enabled, SamAccountName, manager, whencreated | export-csv C:\test.csv

Windows message box : powershell + WPF

$
0
0

I am working with message box and I want to display 1 to 50 in a column and 50 to 100 in an adjacent column in Message box.

I am using  and $data contains an array from 1 to 100

[System.Windows.Forms.MessageBox]::Show:($data,"status",4)

Thanks in advance

Find device id of NIC through powershell

$
0
0

Hi Guys,

Any way i can find mac address  and device id of physical Nics through powershell 

Regards,

Triyambak


Regards, Triyambak

Permission denied only when PSRemoting

$
0
0

Hi,

I want to run a command remotely but when I do it, it gives me a permission denied.

Invoke-Command -Credential (Get-Credential) -ComputerName srvdfs02 -ScriptBlock { Get-DfsnFolder -Path "\\pierre.be\homes\xxxxxx"}

The credential used is domain admin and have full right on all. When I run the Get-DfsnFolder command directly on the server, it works well. But, if I do a PSSession, enter into it and run the command it gives me the same error than the invoke-command.

So,

Directly -> OK

By Enter-pssession -> Fail

By Invoke -> Fail

Have you got any idea ?

Regards,

Arnaud H.

Powershell script for AD help

$
0
0

Hi All,

I am trying to disable over 2 million unused Window accounts in Active Directory.  I have a powershell command I am running but it keeps on timing out.  To make this simple, I want to use command #1 example that I found from a Microsoft article.  Command #2 is the command I am running that keeps on timing out.  I want to insert it into command # 2, into Command # 1, but I am unsure where to add it or paste it.  Hoping someone can help me with this. 

Thanks for your help in advance,

TT

Command # 1: (I want to use this com # 1, however, I don't know where to copy and paste the parts in Com # 2, into Com # 1.  Also, if I need to delete any parts from Com # 1. ) 

$adobjects = get-aduser -Filter {-NOT(UserAccountControl -band 2)} -ErrorAction Stop; $adobjects | ForEach-Object {Start-Sleep -Milliseconds 200; $_}

Command # 2: (timing out command)

Get-ADUser -Filter 'Name -like "*"' -SearchBase "OU=users,DC=Test,DC=abc,DC=ca,DC=com" | Disable-ADAccount

Here is the article I found below:

http://social.technet.microsoft.com/wiki/contents/articles/32418.active-directory-troubleshooting-server-has-returned-the-following-error-invalid-enumeration-context.aspx

 



Outputting to Multiple Arrays to CSV

$
0
0

I have written a script that will look into a configuration file, grab PC name, Sockets, Available Socket and if there are any duplicates.

The issue is if we clean up the duplicates...  we get a ton of errors.  Technically the script still works, but the OCD in me still wants to clean it up.

Here are the troubling areas:

try { $Duplicates = $list | Group Asset | Where-Object {$_.Count -gt 1} | Select-Object Name #>$null } catch { $Duplicates = "No Duplicates" } Write-output "Asset Tag,PTTYs,,Available PTTYs,Duplicate Asset Tags" | out-file c:\test\Host.csv -Encoding ASCII -Append for ($i=0; $i -le $list.count; $i++) { Write-output "$($list[$i] | Select-Object -ExpandProperty Asset),$($list[$i] | Select-Object -ExpandProperty PTTYs),,$($missing[$i] | Select-Object -ExpandProperty Unused),$($Duplicates[$i] | Select-Object -ExpandProperty Name)" | out-file c:\test\Host.csv -Encoding ASCII -Append }

I have narrowed it down to the for loop.  How would I set it up so if that the duplicate array is empty, it will just print out a blank space and thus getting ride of the errors.


Search-ADAccount -PasswordExpired isn't returning users whose password has expired

$
0
0

I'm trying to use PowerShell to identify users whose passwords have expired, and I came across a very elegant one-liner via the Scripting Guy's blog:

Import-Module ActiveDirectory
Search-ADAccount -PasswordExpired


Unfortunately, this doesn't seem to return any users, even though I know there are some with expired passwords, which I can validate with the following code:

#Get Users From AD who are enabled
Import-Module ActiveDirectory
$users = get-aduser -filter * -properties * |where {$_.Enabled -eq "True"}

foreach ($user in $users)
{

 if ($user.passwordexpired -eq "True")
 {
  write-host $user.displayname " Password Has Already Expired"

 }
}

Is anyone able to explain why the first script doesn't return anything but the second does? Whilst I have a working solution, I'm keen to understand why the first doesn't return anything.

Thanks in advance,

  Andy


Trying to convert from Get-WmiObject to Get-CimInstance

$
0
0

I've been watching some of Don Jones' Powershell videos on Youtube and he said you should not use Get-WmiObject anymore since it has been deprecated. He said to use Get-CimInstance. I tried that but I can't get PS to connect to a remote computer. The error mentions verifying that the WS-Man service is running and to make sure WinRM is running as well. It mentions running winrm quickconfig but I would have to remote into the system to do it. Our Enterprise systems are not setup to allow PSRemoting and we would have to create a GPO to set it up correctly, which takes weeks to get pushed through our Change Control. Any other suggestions? I can't get New_CimSession to work either - same error.

Brian

I dont understand why I get the following: New-ADComputer : A required privilege is not held by the client

$
0
0

Hi,

I'm a Domain Admin logged-on to a 2008 R2 RWDC.  Through the Active Directory Users and Computers interface I can add a new Computer object with no issue.  When I issue the following New-ADComputer PS cmdlet, I get the following error which I cant figure out why Im getting it.  Any ideas?

New-ADComputer : A required privilege is not held by the client
At C:\Utils\CreateObj.ps1:157 char:15
+ New-ADComputer <<<<  -Name $Comp USSQLDB1
    + CategoryInfo          : NotSpecified: (CN=USSQLDB1,OU=...us,DC=Fly,DC=by:String) [New-ADComputer], ADException
    + FullyQualifiedErrorId : A required privilege is not held by the client,Microsoft.ActiveDirectory.Management.Commands.N
   ewADComputer


Thanks for your help! SdeDot

Scripts with several parameters that require unc path, strings with spaces and array of values

$
0
0

I wrote a script that is supposed to have several parameters needed in order to create and assign folder access.

The script looks like this:

script.ps1 -FullPath "\\unc\path with\spaces\" -Maingroup "String with space" -Subgroup "string.number" -Users user1,user2,user3

Where -Fullpath is a string with UNC path and spaces

-Maingroup is a string with spaces

and -Users is an array that contains at least 1 value (but can contain more)

I define the parameters like this:

Param([string]$FullPath, [string]$MainGroup, [string]$SubGroup, [string[]]$Users)

However, when I try to run it, I tried two ways and both gave me different errors:

powershell.exe "c:\scripts\powershell\script.ps1" -FullPath "\\unc\path with\spaces\" -Maingroup "String with space" -Subgroup "string.number" -Users user1,user2,user3

(it errors out saying that there there is a missing terminator ")

powershell.exe -file "c:\scripts\powershell\script.ps1" -FullPath "\\unc\path with\spaces\" -Maingroup "String with space" -Subgroup "string.number" -Users user1,user2,user3

(it errors out saying that object 'String' (from String with space) is invalid. This means it seems to take the unc path properly but it cannot handle the "String with space" properly).

Any insights on how to solve this?

Thanks.

Run From Current Directory - Match Strings

$
0
0
hi friends,

I would like to run this from the current directory.

My script matches all the lines that have  TW5ZX8 and then out puts them to a file.

Error cannot find path

$Files = (dir *.txt)

$OutputFile ="C:\Users\Dan\Desktop\output.txt"        # Output file Name

$Pat1 = 'TW5ZX8'

Remove-Item "$OutputFile"

Get-ChildItem -Path "$Files" | Get-Content  | Select-String -Pattern $Pat1 -AllMatches >> "$OutputFile"
I'm not sure what is wrong 
any tips

Cheers Dan


Call Batch File within Powershell

$
0
0

Hi,

 How can I call the batch file from C:\temp and run it on a remote computer?

$comp - "win7machine"

$ping = (test-Connection $comp -quiet)

If ($ping) {

 $cert = get-certs $comp | ?$_.notBefore -gt (Get-Date) -ErrorAction Stop

} Else{

write-host "offline"

If ($cert) {

 "Run a batch file from C:\temp\fix to $comp"

Thank you


Tuan


Powershell GUI help

$
0
0

First off, I am not a powershell expert at all.  I have been trying to learn and decided to write a simple script our helpdesk people can use when a user leaves the company.  The script works great, I am now trying to create a simple GUI but can't for the life of me figure out how to make it work.  I have been on Google for the past day and haven't found any solution.  I think it is more my own ineptitude than anything else.  I am not a programmer, just a lowly sysadmin.  Anyway, this is the original script and it works great.

#Script for user unenrollment.  Will automatically check if the H:\ drive is empty, disable the AD account and generate the 3 week removal ticket

$user = Read-Host 'Enter the username'
$Ticket = Read-Host 'Enter ticket number'
$3week = (get-date).AddDays(21).ToString("MM-dd-yyyy")

$SearchRoot = "\\file_Server\Folder\$user"

#Check if H:\ Drive is empty

Get-Item -Path $SearchRoot | ForEach-Object {
   if ($_.PSIsContainer -eq $true) {
      if ((Get-childItem -Path $_.FullName) -eq $null) {
        Write-Host "$($_.FullName) is empty."
   } else {
      Write-Host "$($_.FullName) is not empty."
        }
            }
                }

#Disable AD Account
#First get username from displayname and set as variable
$ADName = (Get-ADUser -filter { DisplayName -eq $user }).samAccountName
Disable-ADAccount -identity $ADName -Confirm

#Create 3 week removal notice
##############################################################################
$From = "mickey.mouse@company.com"
$To = "helpdesk@company.com"
$Subject = "$3week - $user ($adname) -  3 Week Removal Notice"
$Body = "Original ticket #$ticket"
$SMTPServer = "mailserver.company.com"
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer `
##############################################################################

<EDIT>I am unable to post pictures or links otherwise I would include a screenshot of the GUI I created.

Now, what I would like to do is be able to run this in a GUI.  XML code for the GUI I created is below.


And here is the XAML code:

<Window x:Class="User_Unenrollment.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:User_Unenrollment"
        mc:Ignorable="d"
        Title="User UnEnrollment" Height="306.25" Width="228.79"><Grid><TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="21" Margin="19,51,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="177"/><Label x:Name="Name" Content="User's Full Name" HorizontalAlignment="Left" Height="24" Margin="58,22,0,0" VerticalAlignment="Top" Width="116"/><TextBox x:Name="textBox2" HorizontalAlignment="Left" Height="21" Margin="52,130,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="116"/><Label x:Name="Ticket" Content="Track-it Ticket #" HorizontalAlignment="Left" Height="24" Margin="64,101,0,0" VerticalAlignment="Top" Width="116"/><Button x:Name="unenroll" Content="UnEnroll!" HorizontalAlignment="Left" Height="46" Margin="52,194,0,0" VerticalAlignment="Top" Width="116"/></Grid></Window>

Like I said, I'm at a loss as how to get this working as a GUI.  Any links or input pointing me in the right direction would be greatly appreciated.

PowerShell ISE - NuGet-anyCPU Initialization Failed

$
0
0

I installed the module browser for the ISE but am unable to browse modules on the PowerShell gallery. 

When launching the ISE I receive a message indicating that the module browser requires NuGet-anycpu.exe to interact with NuGet based galleries. Shortly after clicking the Accept button I receive a message that "Initialization failed. Unable to find package provider 'NuGet'.

Any ideas on how to get past this?

I've tried the following:

- Setting 32-bit and 64-bit execution policies to unrestricted
- Launching ISE as administrator
- Successfully installed the NuGet provider via Install-PackageProvider -name NuGet -Force

EWS not returning user created folders

$
0
0

I have a folder in my Exchange Mailbox called 'XYZ'. It exists at the same level as the Inbox. I'm trying to use EWS to get to items in this folder, but I seem to be failing at finding the folder. Here is the code I'm using (with url to company EWS changed :)):

$service = New-Object -TypeName Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.Timeout = 300000
$service.TraceEnabled = $false
$service.Url = New-Object -TypeName System.Uri('https://my.company.invalid/EWS/Exchange.asmx')
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot)
$tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,'XYZ')
$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
$findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)

At this point $findFolderResults should contain 1 item which is the folder I'm wanting to get a handle to, but instead it's empty (TotalCount = 0). FYI, I've also tried Root instead of MsgFolderRoot above with the same results. However, if I change the code to this:

$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(50)
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,'e')
$findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
$findFolderResults.DisplayName

I get back a list of these folders:

Calendar
Conversation Action Settings
Deleted Items
Junk E-Mail
Notes
Quick Step Settings
RSS Feeds
Sent Items
Suggested Contacts
Sync Issues

Which to me indicates I'm successfully finding some folders (the Exchange built-in ones), but not any folders I've created myself.

Any ideas what I'm doing wrong?

help: debugging script

$
0
0

Hi,

i'm new in powershell scripting and i met some pb with my script:

I simplified the  script (https://gallery.technet.microsoft.com/office/PowerShell-to-InstallUninst-0536b17b)  to deploy office 2013 using GPO.

But i always have the same pb: when i run it, it doesn't take care of the options (it seems like it run with setup.exe /?)

here is the script:

#Office 2013 x64

$ProductId='Office15.PROPLUS'
$SourcePath='dfs path'
$AdminFile='dfs path + .MSP'
$LogPath='dfs path'

Function Add-LogEntry ( [String]$Path ,[String]$Message)
{
    Write-Verbose -Message $Message
    # Only write log entry if a path was specified
    If ( $Path -ne '' ) {
        Add-Content -Path $Path -Value "$(Get-Date): $Message"
    } # ( $Path -ne '' )
} # Function Add-LogEntry

# If a Log Path was specified get up a log file name to write to.
If ($LogPath -eq '') {
    [String]$LogFile = ''
} else {
    [String]$LogFile = Join-Path -Path $LogPath -ChildPath "$($ENV:computername).txt"
}

# Is this Office Product already Installed?
[Boolean]$Installed = $False

If ( $env:PROCESSOR_ARCHITECTURE -eq 'AMD64' ) {
    # Operating system is AMD64

    If ( Test-Path -Path "HKLM:\SOFTWARE\WOW6432NODE\Microsoft\Windows\CurrentVersion\Uninstall\$ProductId" ) {
        # 32-bit Office is installed.
        [Boolean]$Installed = $True
    } # ( Test-Path -Path "HKLM:\SOFTWARE\WOW6432NODE\Microsoft\Windows\CurrentVersion\Uninstall\$ProductId" )

} # ( $env:PROCESSOR_ARCHITECTURE -eq 'AMD64' )


 If (-not $Installed) {
    # Sort out the command that will be used to uninstall the product.
    [String]$Command="$(Join-Path -Path $SourcePath -ChildPath 'setup.exe')"
    #If ($AdminFile -ne '') {
        #[String]$Command+=" /adminfile $AdminFile"
    #}

    Add-LogEntry -Path $LogFile -Message "Install $ProductId using $Command started."
   #If ($PSCmdlet.ShouldProcess("Install $ProductId using $Command started")) {
        # Call the product Install.& $Command " /adminfile $AdminFile" 2>&1
        [Int]$ErrorCode = $LASTEXITCODE
   #} # ShouldProcess
    If ($ErrorCode -eq 0) {
        Add-LogEntry -Path $LogFile -Message "Install $ProductId using $Command completed successfully."
    } Else {
        Add-LogEntry -Path $LogFile -Message "Install $ProductId using $Command failed with error code $ErrorCode and message: $Error"
    } # ($ErrorCode -eq 0)
} Else {
    Write-Verbose -Message "$ProductId is already installed."
} # (-not $Installed)

I think the pb comes from the quotes. I tried many changes without success.

Thanks for your help,

Y.

Operator of comparaison on propertie phonenumber

$
0
0

Hello,

I am new with powershell and i'm learning

I have a little problem.

I need to change the format of the phonenumbers of my AD users. 

First, i would make a search to isolate the number I need to change (current format "+33 (0)X XX XX", and i need to change it in "0X XX XX").

So i tried this code :

get-aduser -Properties telephonenumber -Filter 'phonenumber -like "*(0)*"' -SearchBase "ou=Users,dc=domain,dc=com" | select name, telephonenumber

But that return no result.

I think the operator is bad but I cannot find the good operator, I tried everything (-eq, -match, =...)

If I use the same code on the name it works perfectly

Something like this :

get-aduser -Properties telephonenumber -Filter 'name -like "*es*"' -SearchBase "ou=Users,dc=domain,dc=com" | select name, telephonenumber
This code return the User "Test" and his phone number.

When I would have managed that, I will focus on the loop and the string modification!

Thank you by advance for your help !!

SK1

Viewing all 21975 articles
Browse latest View live


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