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

powershell help

$
0
0
hi friends,
i am not good in powershell and i need a help
 in our active directory there are a lot of users which are a members in Groups, 

i need to list the users which are just members in these groups together grp1 and grp2

an Example:
 (user1 is member in domain users group and grp1 )
 (user2 is a member in domain users group, grp1 and grp2) 
in the output of the script i have to see just the user2 
because user2 is member of grp1 and grp2 together
can you help with a script please 

Inventory

$
0
0

I would need script that user runs on computer and it would give information "User", "Serial", "Hostname"

Also if possible it would add that info into to a excel or csv file. I would send this script to multiple users and when they run it, I would have excel list with that information. How would I go about it?

 

Power shell command returning the improper User name format

$
0
0

(get-wmiobject Win32_ComputerSystem –ComputerName "<user pc name>").UserName
is returning the user name in the below format 
<systemname>/<domainname>/<username>

The above User name format will get when i logged in with Microsoft credentials.

When i logged in with Local account to PC, the same command returning the below Username Format
<domainname>/<username> 

Why it is returning <systemname>/<domainname>/<username> when i Logged in with microsoft account in Windows 8.1?


Using WMI Query UserName is invalid

$
0
0
In Windows 8.1 logged on with Microsoft Account, When i execute the below command in the Windows Power shell 
(get-wmiobject Win32_ComputerSystem).UserName

the User Name will be the in the below format as follows.
<systemname>/<domainname>/<username>

System Name: lenovo-pc
DomainName: LENOVO-PC
UserName: TestAccount

The USERNAME and DOMAINNAME are same in the system registry.

Why PC Name is retrieving from the above WMI Query?
How it is associated with the Usernanme?

Get-ADUser does not fetch user when denied read access to Pre-Windows 2000 Compatible access group

$
0
0

I have denied read access to "Pre-Windows 2000 Compatible access" group for an AD user, suppose, Alice. Now I am trying to fetch the user details using Get-ADUser, but it responds with 

Get-ADUser alice

Get-ADUser : Cannot find an object with identity: 'alice' under: 'DC=Agents,DC=com'.

Why can't I access this user? 

Is there any other way to fetch details of such users?


Service created with New-Service does not start

$
0
0

Hello,

I am trying to create a working service using the New-Service cmdlet. I tried a bunch of different examples, I found on the internet like this one from technet:

new-service -name TestService -binaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"-dependson NetLogon -displayName "Test Service"-StartupType Manual -Description "This is a test service."

The service gets created and is listed in services.msc and Get-Service but I cannot start it. Ever. The state changes to "Starting" but that's all.

I tried it on different machines with different Windows- and PowerShell versions using elevated PS-consoles.

Thanks,

Manuel



Change FontSize in Powershell code

$
0
0

I've got the following code that creates an e-mail message in Outlook and opens it:

$ol = New-Object -comObject Outlook.Application

#Create the new email
$mail = $ol.CreateItem(0)

#Optional, set the subject
$mail.Subject = "<subject>"

#Optional, set the body
$mail.Body = "<body>"

#Get the new email object
$inspector = $mail.GetInspector

#Bring the message window to the front
$inspector.Activate()

Now I want to change the FontSize of the message. Is this possible? And how do I do that?

Suggest script to restart SNMP service forcefully

$
0
0

Hi ALl,

I am new to power shell, I have cmdlet to restart the SNMP service forcefully "restart-service snmp -force", could you please suggest script to be saved and executed from power shell to restart SNMP using the mentioned command? Ty for assistance.


Comparison not working for PS Version

$
0
0

Hello,

I have the below code which compares the version of the installed powershell. For some reason, it is not giving me the desired result.

Below is the code:

$req_psver = 2;
    [string]$psver = Get-Host | Select-Object -ExpandProperty Version 
    Write-Host "Detected Powershell Version: $psver"

    if($psver.Major -ge $req_psver)
    {
        Write-Host "Supported Version"
        Write-Log -logfile $logfilename -Message "Supported Powershell Version: $psver"
    }
    else
    {
        Write-Log -logfile $logfilename -Message "Unsupported Powershell Version: $psver"
        Write-Host "Unsupported Version"
        break;
    }

The output I get is "Unsupported Version". The installed version on the host where I am running the script is 5.1.xxxx.xxxx.xx



Thanks, Rajiv Iyer


Test-Path - Why does it log a Warning Event?

$
0
0

Hello,

recently we needed to find an available drive letter and I found a pretty cute solution for it on the Internet:

$driveLetter = Get-ChildItem function:[d-y]: -Name | Where-Object { !(Test-Path $_)} | Get-Random

Although it works fine, it has one disadvantage: Test-Path logs a warning for every time it tests a non-existing drive. 

Log Name:      Windows PowerShell
Source:        PowerShell
Date:          4/17/2019 1:50:19 PM
Event ID:      300
Task Category: Provider Health
Level:         Warning
Keywords:      Classic
User:          N/A
Computer:      myComputer
Description:
Provider Health: Could not find the drive 'k:\'. The drive might not be ready or might not be mapped.. 

Details: 
ProviderName=Microsoft.PowerShell.Core\FileSystem
ExceptionClass=DriveNotFoundException
ErrorCategory=
ErrorId=
ErrorMessage=Could not find the drive 'k:\'. The drive might not be ready or might not be mapped.

Severity=Warning

SequenceNumber=17

HostName=ConsoleHost
HostVersion=5.1.14393.2828
HostId=5af4904e-479c-4cab-8bd0-96de87da8954
HostApplication=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
EngineVersion=5.1.14393.2828
RunspaceId=7b6795b0-c2ba-4f71-8356-1990d0277302
PipelineId=15
CommandName=
CommandType=
ScriptName=
CommandPath=
CommandLine=

I really do not understand this behaviour of Test-Path. I use it to avoid a warning later in the script but Test-Path fires back and writes a warning into the event log, where our Monitoring solution finds it. By the way, "-ErrorAction Ignore" has no impact on it. 

Kind regards,

Jiriki


My Signature


Power Shell Script

$
0
0
I want to create a PowerShell script that will pull out a report of AD user's who changed their lastname and the date of change .   

Configuring IP Address by NIC Model.

$
0
0

hi everyone,

how do i configure an IP address to a specific LAN card, and not by the windows display name? (e.g Ethernet, Ethernet1,etc...)

I've been trying to find an answer in microsoft power shell documentation by i couldn't find what i needs.

in the test lab sometime test engineers are "ghosting" the computers (it's the same procedure as formatting them), and instead of letting them configure the IP statically i would like the power shell to do that automatically after ghost.

in my scenario the test machines are laptops.

the built in network adapter for the laptop is: INTEL Ethernet controller I217-LM

the USB to Lan adapter model name is:ASIX AX88179 USB 3.0 gigabit ethernet Adapter.

I want the power shell to configure the IP address in the ASIX AX88179, and NOT on the Intel adapter how do i tell power shell to do that?


Automatically refresh an Azure (AAD) token

$
0
0

I have a script that is designed to connect to the Power BI (PBI) REST API and refresh the datasets on there, this script was sourced from Guy in a Cube, and while I can follow what its doing the finer points allude me. Ultimately this will form part of another script that will refresh a series of Excel workbooks and then trigger a refresh of the PBI datasets that consume data from the Excel files. My preferred approach would be to just rewrite everything directly in PBI but that's a very big job and this will improve efficiency compared to what is happening at the moment, until the larger goal can be achieved.

The issue I have is with the scheduling of this script and authentication. When in ISE I can run it without issue, but I get a prompt for credentials, although all I'm am doing is selecting my account so presumably my password is stored somewhere on the PC I'm using. When scheduling with Task Scheduler, I do not get this prompt, and really this needs to run unattended anyway, so the goal is to have Task Scheduler run the script without user intervention.

He is the script;

$groupID = "REDACTED"

$clientId = "REDACTED" # End Parameters ======================================= # Calls the Active Directory Authentication Library (ADAL) to authenticate against AAD function GetAuthToken { if(-not (Get-Module AzureRm.Profile)) { Import-Module AzureRm.Profile } $redirectUri = "urn:ietf:wg:oauth:2.0:oob" $resourceAppIdURI = "https://analysis.windows.net/powerbi/api" $authority = "https://login.microsoftonline.com/common/oauth2/authorize"; $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto") return $authResult }# Get the auth token from AAD $token = GetAuthToken # Building Rest API header with authorization token $authHeader = @{ 'Content-Type'='application/json' 'Authorization'=$token.CreateAuthorizationHeader() } # properly format groups path $groupsPath = "" if ($groupID -eq "me") { $groupsPath = "myorg" } else { $groupsPath = "myorg/groups/$groupID" } # Get the datasets on the group $datasetsuri = "https://api.powerbi.com/v1.0/$groupsPath/datasets" $datasets = Invoke-RestMethod -Uri $datasetsuri –Headers $authHeader –Method GET –Verbose | Select-Object -ExpandProperty value | Select-Object id, name

Having stepped through the script I know my issue lies in the part in bold and that ultimately relies the function created above. How do I specific credentials in that function so I do not receive a prompt to enter them?

How to find Fileless Malware

$
0
0

I was reading an article about searching for Fileless Malware (https://www.ultimatewindowssecurity.com/) and I was trying to build a PS script to do it.

I started with this:

$filename=Get-Process -module|selectModuleName,filename

foreach ($filein$filename){

write$file

get-item$file| selectlength |where ($.length-cle'0')}

 

However, line 1 is causing me some grief…

When I run Get-Process, I get this result (as expected):

PS C:\WINDOWS\system32> Get-Process
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName                                                                                   
-------  ------    -----      -----     ------     --  -- -----------                                                                                                     
    384      22    16132      30692       0.23   3528   1 ApplicationFrameHost                                                                           
    457      67    13900      27504       0.88   4836   0 AppVClient                                                                                           
    377      24    45788      44744       0.61   8520   1 AppVStreamingUX                                                                                                                                                                                     


When I run $Filename = Get-Process, I get this result (nothing):

PS C:\WINDOWS\system32> $Filename = Get-Process
PS C:\WINDOWS\system32> 


When I run  Get-Process –module , I this result (as expected):

PS C:\WINDOWS\system32> Get-Process –module
Size(K) ModuleName                                 FileName                                                                                                    

-----    ----------                                       --------                                                                                                             80      ApplicationFrameHost.exe               C:\WINDOWS\system32\ApplicationFrameHost.exe                                       1924   ntdll.dll                                          C:\WINDOWS\SYSTEM32\ntdll.dll                                                                       712    KERNEL32.DLL                                C:\WINDOWS\System32\KERNEL32.DLL                                                                                                                                                                 


When I add the variable on $Filename = Get-Process –module, I get this result (unexpected):

PS C:\WINDOWS\system32> $Filename = Get-Process –module
Get-Process : Cannot enumerate the modules of the "csrss" process.
At line:1 char:13
+ $Filename = Get-Process –module
+             ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (System.Diagnostics.Process (csrss):Process) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : CouldnotEnumerateModules,Microsoft.PowerShell.Commands.GetProcessCommand


I even tried:

  1. invoke-command {Get-Process-module| selectModuleName,filename}” which worked, but once I added the “$filename =” back in it breaks “Cannot enumerate…”.
  2. Get-Process|  ? { (get-process-id$_.id-module| ? {$_.length-cle"0"})}”, but it also breaks “Cannot enumerate…”.

The only possible solution that I may have found is “Get-Process|where {$_.Modules-like'*'} |? {$_.length-cle"0"}” –where it returns no results, but that might just meant that I don’t have any fileless processes running.

Thoughts?



FamilyMan

Pass variable inside runspace

$
0
0

I have two variables that are outside a run space, I would like to know how I can do to pass them into the script block.

thanks in advance

Add-Type -AssemblyName System.Windows.Forms $buttonStart = New-Object 'System.Windows.Forms.Button' $buttonStop = New-Object 'System.Windows.Forms.Button' $timer = New-Object 'System.Windows.Forms.Timer'

$Target = '192.168.10.12'

$count = 10

$BGScriptBlock = { for ($i=0;$i -lt $count; $i++){ $tc = (Test-Connection -ComputerName $Target -Verbose -Count 1) $reply = "#" + $i+ "`tAddress: " + $tc.Address + "`tSize: " + $tc.ReplySize + "`tTime: " + $tc.ResponseTime + "ms`r`n" $synchash.form.Controls[2].Text = $reply + $synchash.form.Controls[2].Text start-sleep -Seconds 1 } return "OK" } $Global:synchash = [Hashtable]::Synchronized(@{ }) $script:Powershell = [PowerShell]::Create().AddScript($BGScriptBlock).AddArgument($PC) $sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault() $runspace = [RunspaceFactory]::CreateRunspace($sessionstate) $runspace.ApartmentState = "STA" $runspace.ThreadOptions = "ReuseThread" $runspace.Open() $runspace.SessionStateProxy.SetVariable("synchash", $synchash) $Powershell.Runspace = $runspace $buttonStart_Click = { $script:AsyncResult = $Powershell.BeginInvoke() $timer.Enabled = $true; $timer.Start(); $script:tick = 0 } $buttonStop_Click = { $Powershell.Stop() $Form.Text = 'Stopped' $timer.Stop() $timer.Enabled = $false } $TimerTick = { $script:tick++; $script:Powershell.InvocationStateInfo.State } $Form = New-Object System.Windows.Forms.Form $Form.Size = New-Object System.Drawing.Size(600,400) $Form.StartPosition = "CenterScreen" $Form.Text = 'Form' $Form.Topmost = $true $timer.Interval = 1000 $timer.add_Tick($TimerTick) $synchash.form = $Form $Button = New-Object System.Windows.Forms.Button $Button.Location = New-Object System.Drawing.Size(20,30) $Button.Size = New-Object System.Drawing.Size(110,80) $Button.Text = "START" $Button.BackColor = "LightGreen" $Button.Cursor = [System.Windows.Forms.Cursors]::Hand $Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.drawing.FontStyle]::Bold) $Button.Add_Click($buttonStart_Click) $Form.Controls.Add($Button) $StopButton = New-Object System.Windows.Forms.Button $StopButton.Location = New-Object System.Drawing.Size(140,30) $StopButton.Size = New-Object System.Drawing.Size(110,80) $StopButton.Text = "STOP" $StopButton.BackColor = "Red" $StopButton.Cursor = [System.Windows.Forms.Cursors]::Hand $StopButton.Font = New-Object System.Drawing.Font("Calibri",11,[System.drawing.FontStyle]::Bold) $StopButton.Add_Click($buttonStop_Click) $Form.Controls.Add($StopButton) $outputBox = New-Object System.Windows.Forms.TextBox $outputBox.Location = New-Object System.Drawing.Size(10,180) $outputBox.Size = New-Object System.Drawing.Size(565,100) $outputBox.MultiLine = $True $outputBox.SelectionStart = $outputBox.Text.Length; $outputBox.ScrollToCaret() = $true $outputBox.ScrollBars = "Vertical" $outputBox.Text = "" $Form.Controls.Add($outputBox) $Form.ShowDialog() $Form.add_FormClosing({ $Powershell.Dispose() $runspace.Close() })





Form DataGridView AutoSizeMode / Resize Form Width to Fit

$
0
0

Hi,

I'd really like a bit of help as I've been going around in circles trying to figure this out...
Basically I have a simple form with a 3-column datagridview.  It potentially has a varied number of rows based on the info provided (this is working fine).

All 3 columns could vary in width potentially so I'd like to be able to setup a form where the datagridview columns are autosize-able and then the form width is adjusted accordingly on load.

I thought I was close to getting this working but just can't seem to finish it off.  It feels like I need to return the column widths after they've been created and populated with data but when I try to do that they always return as 100 which is the default size and not the rendered size so I can't tell the form how wide it actually needs to be.

I can't easily post a semi-working source as it pulls data in from SCCM and Active Directory so if someone could give some idea on how this might be achievable (or if it's achievable at all) in any basic fashion then that would be fantastic.

Stuart

Getting output from a custom psobject

$
0
0

Hi,

I am running the script below retrieving data from an Oracle SQL db. I am intending on putting the values into AD attributes for users. However, I cannot figure out how to read/get the variables for the set-aduser command.

I thought I could go through using foreach, or foreach-object $result.username for example, but it is asking me for the process[0] which I understand it is looking for which object I want in the array...

I would really appreciate some help, I have been trying various things for hours, none of which is working and I have a deadline of course.

Thanks for any help!

$result = @{}

$result = $SelectDataTable | foreach {
    $row = $_;  
    new-object psObject -Property @{ 
        UserName = $_.GetString(2)
        Title = $_.GetString(3)
        Department = $_.GetString(4)
    }
}

New-PSDrive to SPO credentials not working

$
0
0

I need the script below to authenticate with OneDrive for Business and a Sharepoint Online library so I can in the location to my Quick Access links in Windows Explorer. 

The script works if I've already authenticated, but if it's not already authenticated the "-credential" property doesn't pass the information on. I get error"The operation being requested was not performed because the user has not been authenticated".

$creds = Get-Credential
New-PsDrive -Name N -Root "\\OURTENANT.sharepoint.com@SSL\sites\TEST" -PSProvider FileSystem -Credential $Creds
New-PSDrive -Name I -Root "\\OURTENANT-my.sharepoint.com@SSL\personal\' + $env:username + '_OURDOMAIN_org\Documents" -PSProvider FileSystem -Credential $Creds
Get-PSDrive N,I | Remove-PSDrive
$folder = "\\OURTENANT.sharepoint.com@SSL\sites\TEST"
$folder2 = '\\OURTENANT-my.sharepoint.com@SSL\personal\' + $env:username + '_OURDOMAIN_org\Documents'
$QuickAccess = New-Object -ComObject shell.application
$QuickAccess.Namespace($folder).Self.InvokeVerb("pintohome")
$QuickAccess.Namespace($folder2).Self.InvokeVerb("pintohome")

How to use powershell click on outerhtml div class

$
0
0

Hi I'm a rookie to Powershell and I would like to apologize everyone here if I ask the wrong question in the wrong section. Please guide me and help out for my question. 

I wonder possible by using powershell can I can click the button that I want but I found the source code there a little bit complex as below:

<div dijitReset dijitInline dijitLeft dijitTextBox dijitComboBox dijitTextBoxFocused dijitComboBoxFocused dijitFocused" id="widget_manifest" role="combobox" aria-expanded="true" aria-labelledby="manifest_label" widgetId="manifest"><div dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer dijitHasDropDownOpen" role="presentation" data-dojo-attach-point="_buttonNode, _popupStateNode" popupActive="true"><input tabindex="-1" dijitInputField dijitArrowButtonInner" role="presentation" type="text" readonly="readonly" value=""></div><div dijitValidationContainer"><input tabindex="-1" dijitInputField dijitValidationIcon dijitValidationInner" role="presentation" type="text" readonly="readonly" value="Χ "></div><div dijitInputField dijitInputContainer"><input tabindex="0" dijitInputInner" id="manifest" role="textbox" aria-haspopup="true" aria-invalid="false" aria-required="true" aria-owns="manifest_popup" type="text" value="" data-dojo-attach-point="textbox,focusNode" autocomplete="off"><input type="hidden" value=""></div></div>

Please guide me base on the source code above and I hope a good comment is much better than critics. thanks

Powershell Script fails in v.2

$
0
0

We are trying to update our BIOS within a task sequence and i have a script provided by Lenovo which is working fine in Windows 10 and Powershell V5 however it is not working properly in Win 7 with powershell V2. We cant upgrade to V5 on the Win 7 machines right now.

The scripts reads an xml file i have exported from the SCCM and matches the appropriate BIOS package , downloads it and runs it.

So the script looks like :

[xml]$Packages = Get-Content BIOSPackages.xml

# Environment variable call for task sequence only
   
    $tsenv = New-Object -ComObject Microsoft.SMS.TSEnvironment
    
    $BIOS = (Get-WmiObject -Namespace root\cimv2 -Class Win32_BIOS).SMBIOSBIOSVersion.Substring(0,4)

    $ns = New-Object Xml.XmlNamespaceManager $Packages.NameTable

    $ns.AddNamespace( "def", "http://schemas.microsoft.com/powershell/2004/04" )

    $Xpathqry="/def:Objs/def:Obj//def:MS[contains(.,`"$BIOS`")]"

    $Package = ($Packages.SelectNodes($xpathqry,$ns))

    $PackageID = $Package.SelectNodes('def:S[contains(@N,"PackageID")]',$ns)

    $tsenv.Value('OSDDownloadDownloadPackages') = $PackageID.InnerXML

Unfortunately it is failing at: 

 $PackageID = $Package.SelectNodes('def:S[contains(@N,"PackageID")]',$ns)

and i get the error :

Method invocation failed because [System.Xml.XPathNodeList] doesn't contain a m	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)
ethod named 'SelectNodes'.	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)
At C:\_SMSTaskSequence\Packages\NC1002CB\Get-BIOSPackages.ps1:17 char:38	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)+     $PackageID = $Package.SelectNodes <<<< ('def:S[contains(@N,"PackageID")]'	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)
,$ns)	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)+ CategoryInfo          : InvalidOperation: (SelectNodes:String) [], Runti 	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)
   meException	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)+ FullyQualifiedErrorId : MethodNotFound	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)
 	RunPowerShellScript	17/04/2019 15:28:58	7164 (0x1BFC)

I am by no means powershell expert however i have tried to fudge with it for a day and i am just hitting a wall.

Any help with reformulating the failing part 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>