1

完全な開示: 私は Ruby をよく知りません。私はほとんどそれを偽造しています。

多数の Mac を管理するために使用している Casper でインベントリを収集するために使用したいスクリプトがあります。を使用して変数をシェル コマンドに渡そうとしています%x。問題は、Ruby が変数を代わりにコメントとして扱っていることです。関連するコードは次のとおりです。

def get_host
 host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
 raise Error, "this machine must not be bound to AD.\n try again." if host == nil
end

def get_ou
  host = get_host
  dsout = %x(/usr/bin/dscl /Search -read /Computers/#{host}).to_a
  ou = dsout.select {|item| item =~ /OU=/}.to_s.split(",")[1].to_s.gsub(/OU=/, '').chomp
end

の代わりにバックティックを使用してみ%xましたが、同じ結果が得られました。このコマンドは、それが実行されているホストに関する一連の情報を返す必要がありますが、代わりに の結果を返します。dscl /Search -read /Computersこれは常にname: dsRecTypeStandard:Computersです。

どうすればやりたいことを達成できますか?

4

1 に答える 1

5

問題はここにあります。Ruby は常にメソッドの最後の式を返します。

def get_host
  host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
  raise Error, "this machine must not be bound to AD.\n try again." if host == nil
end

この場合、最後の式は次のとおりです。

raise Error, "this machine must not be bound to AD.\n try again." if host == nil

ifの戻り値を返しますraise(実際には発生しません) または ifをhost == nil返します。したがって、メソッドは 以外のものを返すことはありません。それを次のように置き換えます。nilhost != nilnil

def get_host
  host=%x(/usr/sbin/dsconfigad -show | /usr/bin/awk '/Computer Account/ {print $4}').chomp
  raise Error, "this machine must not be bound to AD.\n try again." if host == nil
  host
end
于 2012-05-09T21:23:27.673 に答える