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

script to find the PwdLastSet for the local admin on all servers

$
0
0

HI, does anyone know of a script or a way to find out the last time the local administrators password was reset on all servers?

thx

jason


powershell command to get a list of users created in one month that belong to a specific group or not belong to the specific group.

$
0
0

Powershell command to get a list of users created in one month that belong to a specific group or not belong to the specific group.

How do you Import a file into a variable on Powershell

$
0
0
 Hello I have a question How can I Import a  file into a variable?

How can I pass the rename-computer credential in a powershell script (.ps1)?

$
0
0

Hello everyone,

How can i give the password to "rename-computer" for the "-domaincredential" attribute in the powershell script,?

There are no properties/methods like "-password" (eg image)

I want the script to execute silently, the without HAVING to Manually The Enter password that Needs to be encrypted.

I have read the links below,  but still confused How to Write the completely command in .ps1
: HTTPS: //stackoverflow.com/questions/23482389 /entering-a -password-for-domaincredential-in-rename-computer -in-powershell?Noredirect = 1&lq = 1
https://stackoverflow.com/questions/13842611/how-to-pass-credentials-to-rename- Command

I wrote the following, but it n't work to rename my computer name.

$path=\\sc\cont
$computername="CN-D"+$number
$currentname=(Get-CimInstance -ClassName Win32_ComputerSystem).Name
$user="sc\joindomain"
$encpwd = Get-Content $path\password.bin
$passwd = ConvertTo-SecureString $encpwd
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $passwd
if($computername -ne $currentname){
    Rename-Computer -NewName $computername -DomainCredential $credential
}

Thank you in advance.

Import-WdsInstallImage : An install image could not be found in the image file

$
0
0

As asked from here I ask my question on the PowerShell forum.

Hello,

The WDS server is a freshly installed Win 2019 server.

I am trying to import install images with PowerShell.

$ImagePath = 'D:\Sources\2019\install.wim'
$ImageName = (Get-WindowsImage -ImagePath $ImagePath -Index 4).ImageName
Import-WdsInstallImage -ImageGroup 'Win2019' -ImageName $ImageName -Path $ImagePath -Multicast

However I get the following error:

Import-WdsInstallImage : An install image could not be found in the image file.
At line:3 char:1+ Import-WdsInstallImage -ImageGroup 'Win2019' -ImageName $ImageName -P ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (MSFT_WdsInstallImage:root/cimv2/MSFT_WdsInstallImage) [Import-WdsInstallImage], CimException+ FullyQualifiedErrorId : 0xC111010E,Import-WdsInstallImage

The image file is NOT read-only.

And with the console it works fine.

I also installed the latest system rollup, but the behavior is the same.

I first started to display image names with Get-WindowsImage and copy/paste the name to the Import-WdsInstallImage and got the same error. That's why I was getting directly the name from the Get-WindowsImage cmdlet. But no luck, still the same error...

And while the Import-WdsInstallImage returns an error, the Import-WdsBootImage and theGet-WindowsImage cmdlets are works fine.

Does anybody see what's wrong with my code or my command lines?

Formatting the output of the script

$
0
0

I have create a script that fetches the name of AD Object, however there are some user defined properties in the objects that requires some formatting initially I was simply loading the properties and the data was obtained in proper tabular structure.

Get-ADGroup -Filter { 'objectClass' -eq 'grp' } -Properties Name, GUID | Select Name, GUID

From the script above the data will be loaded in this format

Name             GUID

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

Test              ABCD-1234-XXXX

Test2            JKLM-4567-YYYY

I have a function that I am using to count the days let say do operation on the group after some x days. So, the count of x is fetched through that function. Say CountX(). 

So, my script is somewhat like.

$ADGROUP = Get-ADGroup -Filter { 'objectClass' -eq 'grp' } -Properties Name, GUID | Select CountX(GUID) +" - "+ Name, GUID

function CountX($ADGroup){

#SomeOperations Counting the DueDate return $DueDate #Lets Say The Date is in the format "yyyy/MM/dd" }

$ADGroup | Select-Object -Join (CountDueDate($ADGroup), Name), ObjectGUID // Concatenating Name & Date String()

But the script is causing the error :  The term 'CountDate' is not recognized as the name of a cmdlet, function, script file, or operable program. I think I am not invoking my function properly. Any Suggestions?

My Expected Output is Suppose to be:

Name                                GUID

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

2019/01/01 Test               ABCD-1234-XXXX

2019/01/01 Test2             JKLM-4567-YYYY


Need to Copy all treeview nodes(which are "checked") when i hit the command button using powershell.

$
0
0

Hi,

I am not able to find direct powershell command to copy the all treeview nodes(which are "checked") when i hit the command button. kindly advice and share the script for achieving the task. thanks.

Regards,

Senthil kumar R. 

ADAL token problem when connecting to PowerBI Service via API from powershell

$
0
0
hi, 

I'm trying to connect to powerBI by using API from powershell.

this is the code that I'm using:

$common = $PSScriptRoot + "\common.ps1"
. $common

##set parent directory for this file
#set project setting file
$parentfDir = Split-Path $PSScriptRoot -Parent 
$confDir = getFilePath $parentfDir "\json\automation_tools_seting.json"

#get project settings and package parameter
$conf = loadJsonFile $confDir

$user = $conf.PBI_user
$pass = $conf.PBI_pass | ConvertTo-SecureString -asPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential ($user, $pass)
try {
    Connect-PowerBIServiceAccount -Credential $credential

    Disconnect-PowerBIServiceAccount
}
catch {
   Write-Output "$($_.Exception.Message)"
}

but it always has an error :
Connect-PowerBIServiceAccount : Failed to get ADAL token:


wondering if there's way to fix this problem



script to send email to user with their multiple email addresses

$
0
0

Hi 

i got the script below which mainly email users about their current SMTP addresses (multiple ones) and ask them which one they dont need

$Msg.To.Add($ToAddress)
$Msg.Subject = "Email Addresses Clean up"
$Msg.Body = $EmailBody
$Msg.IsBodyHTML = $true
$Smtp.Send($Msg)
}
# Define local Exchange server info for message relay. Ensure that any servers running this script have permission to relay.
$ExchangeServer = "mail.hwl.com.au"
$FromAddress = "it.helpdesk@hwle.com.au"
# Import user list and information from .CSV file
$Users = Import-Excel testfinalsmtpaddress.xlsx
# Send notification to each user in the list
Foreach ($User in $Users) {
$ToAddress = $User.PrimarySmtpAddress
$Name = $User.DisplayName
$EmailAddresses = $User.EmailAddresses
$EmailBody = @"
<p style='font-size:10.0pt;font-family:"Arial",sans-serif'>Dear $Name.<o:p></o:p></span></p>
<p style='margin-left:18.0pt;text-indent:-18.0pt;
<![if !supportLists]><span style='font-size:10.0pt;
font-family:Symbol;<span
style='·<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span></span></span><![endif]><span style='font-size:10.0pt;font-family:"Arial",sans-serif'>The
following is a list of email addresses which are currently attached to your

mailbox.<o:p></o:p></span></p>

Email Addresses: $EmailAddresses

The list of users with multiple smtp addresses have been generated and it is in excel format with each email have been displayed follow line break like this

Problem is when I send an email to them using this function to display their email addresses Email Addresses: $EmailAddresses, all their smtp address does not display one by one with line break, it seem to combine them into one long line which make difficult for user to read. The excel spreadsheet which contains smtp addresses already got correct format 

I just wonder if anyone know how can I overcome that?

Name                                                                                                  Primary Email                                               EmailAddresses                                                                                                 

Hung Nguyen

hnnguyen@hwle.com.au

  jmarz@tresscox.com.au
  jmarz@lawsonsmith.com.au
  jmarz@abbotttout.com.au
  jmarz@hwl.com.au
  jmarz@cridlandsmb.com.au
  jmarz@hwlebsworth.com
  jmarz@hwlebsworths.com
  jmarz@hwlebsworths.com.au
  jmarz@ebsworths.com.au
  jmarz@kellyco.com.au
  jmarz@downingslegal.com.au
  jmarz@downings.com.au
  jmarz@hwlebsworth.com.au
  joseph.marz@hwle.com.au
  Joseph.Marz@hwlebsworth.com.au
  JMarz@ebsworth.com.au
  Joseph.Marz@hwl.com.au

PoshRSJob not passing $computer

$
0
0

I have a script to check services from a list of computers:

$winrmlist =  import-csv .\computers.csv | select-object -expandproperty computer

 Foreach ($computer in $winrmlist) {
          $winrmsvc=get-service -Computername $computer -name winrm
          $rpcsvc=get-service -computername $computer -name rpcss
          $remotereg=get-service -Computername $computer -name RemoteRegistry

               if ($Winrmsvc.status -eq "stopped") {
                  write-host $computer $winrmsvc $winrmsvc.status -foregroundcolor red} else {
                   write-host $computer $winrmsvc $winrmsvc.status -foregroundcolor green}

               if ($rpcsvc.status -eq "Stopped") {
                   write-host $computer $rpcsvc $rpcsvc.status -foregroundcolor red} else {
                   write-host $computer $rpcsvc $rpcsvc.status -foregroundcolor green}                  

               if ($remotereg.status -eq "Stopped") {
                   write-host $computer $remotereg $remotereg.status -foregroundcolor red} else {
                   write-host $computer $remotereg $remotereg.status -foregroundcolor green} 

 }

works fine for what I need but, could use some error catching.

Anyhow, I downloaded PoshRSJob and, am just trying to understand how I could get it to work with this script.

I tried a number of iterations of 

$winrmlist =  import-csv .\computers.csv | select-object -expandproperty computer

$winrmlist | forEach-object {Start-rsjob -name {$_.computer} -Scriptblock {
Param($object)
$winrmsvc=get-service -Computername $object -name winrm
          $rpcsvc=get-service -computername $object -name rpcss
          $remotereg=get-service -Computername $object -name RemoteRegistry

I also tried:

$winrmlist | forEach-object {Start-rsjob -name {$_.computer} -Scriptblock {
Param($object)
$winrmsvc=get-service -Computername $_ -name winrm
          $rpcsvc=get-service -computername $_ -name rpcss
          $remotereg=get-service -Computername $_-name RemoteRegistry

I cant seem to get it to pass the $computer

Can someone point me in the right direction?

Thank you!

Steve


--------- SteveP

How to get the list of Azure AD groups that user belongs to

$
0
0

Hi All,

I want to get list of Azure AD groups that user belongs to. how to get this with powershell scripting.

Thank you.

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

$
0
0

Hi All, i am getting the below errors when i am running my script. Can you please help me its urgent. 

Code- 
$diskD = Get-WmiObject Win32_LogicalDisk -ComputerName $destinationIP -Filter "DeviceID='D:'"
$disk =  Get-WmiObject Win32_LogicalDisk -ComputerName $localhost -Filter "DeviceID='C:'"

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:16 char:10
+ $diskD = Get-WmiObject Win32_LogicalDisk -ComputerName $destinationIP ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

 

New-Item : The network path was not found
At line:51 char:5
+     New-Item -ItemType Directory -Force -Path $TestFolderPath
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (\\​192.168.166.106\\d$\BackUp_Logs:String) [New-Item], IOException
    + FullyQualifiedErrorId : CreateIntermediateDirectoriesIOError,Microsoft.PowerShell.Commands.NewItemCommand

 
New-Item : The UNC path should be of the form \\server\share.
At line:51 char:5
+     New-Item -ItemType Directory -Force -Path $TestFolderPath
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (\\​192.168.166.106\\d$:String) [New-Item], ArgumentException
    + FullyQualifiedErrorId : CreateDirectoryArgumentError,Microsoft.PowerShell.Commands.NewItemCommand

How come I cannot run this basic powershell command?

$
0
0

Hi - I'm just trying to get used to running some basic troubleshooting commands in powershell so wanted to load up the logs. I tried a couple from Event viewer. System I can kind of understand but what about the SECURITY log? Do certain services have to be stopped before running the security log for troubleshooting purposes? 

Thanks in advance

How to update static DNS IPs for servers in specific OU in Active Directory

$
0
0
I am trying to update static DNS IP addresses for all my servers in specific OU in Active Directory. I need help putting the GetComputer command with the Set-DNSClientServerAddress command so that I can only update the handful of servers I need to from old DNS IPs to new. 

Script RDP connexion that start another RDP connexion

$
0
0

Hi all,

I'd like to find a script that will create an RDP connexion to a server1, and from this server1 the script must create another RDP connexion from a server2.

I can't create an RDP connexion to server2 directly because of firewall rules. so i have to pass through server1.

I'd like that when i start my script i'm reaching server2 directly (as if server1 doesn't exist)

I hope i'm clear enough.

Thx for your help.


s



Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

$
0
0

I'm using below query for download but i got below error can you please suggest me how to resolve this issue.

Query:

(new-object -comobject "microsoft.update.session").CreateUpdateDownloader()

Error:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

At line:11 char:5
+     $downloader = $updateSession.CreateUpdateDownloader()


Change Time execute program then change time back

$
0
0

I have an application that I need to change system time and date.

Then execute the program, once executed successfully I need to change the system time and date back to another state.

Can I do this in powershell, if so how.

Thanks

Script no longer works - You cannot call a method on a null-valued expression.

$
0
0

I ran this script a few months ago, and now I get an "You cannot call a method on a null-valued expression." error in my stderr.csv file, and nothing in my stdout.csv file. I would appreciate guidance on this. The service I am after has been replaced with the generic "ServiceName" Thanks.

$strMachineName = import-csv -LiteralPath C:\Intel\AllServers_Date.csv
foreach ($line in $strMachineName)
{
    try {
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $line.computer)
        $regkey = $reg.OpenSubkey("System\\CurrentControlSet\\Services\\ServiceName")
        $serialkey = $regkey.GetValue("ImagePath")

        ('"{0}","{1}"' -f $line.computer, $serialkey) | out-file C:\stdout.csv -append -encoding ascii
    } catch {
        ('"{0}","{1}"' -f $line.computer, $_) | out-file C:\stderr.csv -append -encoding ascii
    }
}


A specified logon session does not exist. It may already have been terminated

$
0
0

Hello, everyone! I recently meet a strange problem about double hop.

I try to run the following PowerShell command

$credential = Get-Credential

$computerName = "frxp02361Dmbssh"

$psdrive1 = @{
    Name = "PSDrive1"
    PSProvider = "FileSystem"
    Root = "\\mbssh01\Tool"
    Credential = $credential
}

$psdrive2 = @{
    Name = "PSDrive2"
    PSProvider = "FileSystem"
    Root = "\\dyn\AX"
    Credential = $credential
}

$psdrive3 = @{
    Name = "PSDrive3"
    PSProvider = "FileSystem"
    Root = "\\scmlabe3\SCM"
    Credential = $credential
}

$psdrive4 = @{
    Name = "PSDrive4"
    PSProvider = "FileSystem"
    Root = "\\codeflow\public"
    Credential = $credential
}

Invoke-Command -ComputerName $computerName -ScriptBlock {
     New-PSDrive @using:psdrive1
     New-PSDrive @using:psdrive2
     New-PSDrive @using:psdrive3
     New-PSDrive @using:psdrive4
}

Finally, I successfully create new PSDrives of "\\mbssh01\Tool", "\\scmlabe3\SCM", "\\codeflow\public"EXCEPT FOR "\\dyn\AX"

I received the following error:

Name           Used (GB)     Free (GB) Provider      Root                                CurrentLocatio PSComputerNam
                                                                                                      n e
----           ---------     --------- --------      ----                                -------------- -------------
PSDrive1                                             \\mbssh01\Tool                                     frxp02361D...
A specified logon session does not exist. It may already have been terminated+ CategoryInfo          : InvalidOperation: (PSDrive2:PSDriveInfo) [New-PSDrive], Win32Exception+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand+ PSComputerName        : frxp02361Dmbssh

PSDrive3                                             \\scmlabe3\SCM                                     frxp02361D...
PSDrive4                                             \\codeflow\public                                  frxp02361D...

We can see the command "New-PSDrive @using:psdrive2" failed.

But the other three commands all succeed.

I have tested that I can access the folder "\\dyn\AX" in File Explorer when I login into the remote computer.

Can anyone help me? I will be very grateful!




get-date command in powershell

$
0
0

I am trying to create a powershell script that would send email notification advising groups of people servers will be rebooted.

I have the script working with the (Get-date).AddDays(1)  command but it also adds the local time. I just want it to add the it to show the date + 1 day date with  no time. How do you make this  work?

Viewing all 21975 articles
Browse latest View live


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